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.
Related
When i try to set the ImageView variable "profilePicture" to the bitmap from the image url, it doesn't show anything. Please help!! I am getting the image url link from my database. This is what that async task result is.
System.out: Resulted Value: {"image":"http://www.myegotest.com/PhotoUpload/uploads/5.png"}
Here is my Java code
public class HomeActivity extends AppCompatActivity {
//View item variables
private TextView loggedUsersName;
private TextView successMessage;
private Button logoutButton;
private ImageView profilePicture;
//Other variables
private String getProfileImageURL = "http://www.myegotest.com/PhotoUpload/getAllImages.php";
private String firstName;
private String lastName;
private String email;
private Bitmap profilePicBitmap;
LocalDataBase mLocalDataBase;
Boolean imageSet;
Drawable d;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
//Get logged in user from LocalDataBase and
//Destroy Activity if user is logged out
mLocalDataBase = new LocalDataBase(this);
User user = mLocalDataBase.getLoggedInUserInfo();
if(!mLocalDataBase.userIsLoggedIn()){
HomeActivity.this.finish();
}
//Initialize view item variables.
loggedUsersName = (TextView)findViewById(R.id.login_user);
successMessage = (TextView)findViewById(R.id.message);
logoutButton = (Button)findViewById(R.id.logoutButton);
profilePicture = (ImageView)findViewById(R.id.profile_Picture);
//Get intent and values from the intent started this activity and
//Get loggedIn user values from the LocalDataBase .
Intent intent = getIntent();
String message = intent.getStringExtra("MESSAGE");
firstName = user.mFirstName;
lastName = user.mLastName;
email = user.mEmail;
//Set view values to equal values sent from intent.
loggedUsersName.setText(firstName + " " + lastName);
successMessage.setText(message);
netAsync();
}
//Call this method to execute the Async Task
private void netAsync() {
new NetCheck().execute();
}
//Async Task to check whether internet connection is working.
private class NetCheck extends AsyncTask {
private ProgressDialog mDialog;
//Create and show progress dialog box so user knows the app is trying to login.
#Override
protected void onPreExecute() {
super.onPreExecute();
mDialog = new ProgressDialog(HomeActivity.this);
mDialog.setTitle("Logging In...");
mDialog.setMessage("connecting to server");
mDialog.setIndeterminate(false);
mDialog.setCancelable(true);
mDialog.show();
}
//Gets current device state and checks for working internet connection by trying Google.
#Override
protected Boolean doInBackground(Object[] objects) {
ConnectivityManager mCM = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo myNetInfo = mCM.getActiveNetworkInfo();
if ( (myNetInfo != null) && (myNetInfo.isConnected())){
try {
URL url = new URL("http://google.com");
HttpURLConnection myConnection = (HttpURLConnection) url.openConnection();
myConnection.setConnectTimeout(3000);
myConnection.connect();
if (myConnection.getResponseCode() == 200){
return true;
}
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
//If successful internet connection start AsyncTask to register user info on server
if(o.equals(true)){
mDialog.dismiss();
new RegisterUser().execute(getProfileImageURL, email);
} else {
mDialog.dismiss();
Toast.makeText(getApplicationContext(), "Error in Network Connection", Toast.LENGTH_SHORT).show();
}
}
}
//AsyncTask to get profile pic url string from server
private class RegisterUser extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
URL url = new URL(params[0]);
HttpURLConnection LucasHttpURLConnection = (HttpURLConnection)url.openConnection();
LucasHttpURLConnection.setRequestMethod("POST");
LucasHttpURLConnection.setDoOutput(true);
LucasHttpURLConnection.setDoInput(true);
LucasHttpURLConnection.setConnectTimeout(1000 * 6);
LucasHttpURLConnection.setReadTimeout(1000 * 6);
//OutputStream to get response
OutputStream outputStream = LucasHttpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
String data =
URLEncoder.encode("email", "UTF-8")+"="+URLEncoder.encode(params[1], "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
//InputStream to get response
InputStream IS = LucasHttpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(IS, "iso-8859-1"));
StringBuilder response = new StringBuilder();
String json;
while( (json = bufferedReader.readLine()) != null){
response.append(json + "\n");
break;
}
bufferedReader.close();
IS.close();
LucasHttpURLConnection.disconnect();
return response.toString().trim();
} catch (MalformedInputException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Print server AsyncTask response
System.out.println("Resulted Value: " + result);
//If null Response
if (result != null && !result.equals("")) {
String profilepic = returnParsedJsonObject(result);
new GetBitmapImageFromUrl().execute(profilepic);
profilePicture = (ImageView)findViewById(R.id.profile_Picture);
profilePicture.setImageBitmap(profilePicBitmap);
} else {
Toast.makeText(HomeActivity.this, "Sorry, there was an error. Please try again", Toast.LENGTH_LONG).show();
}
}
//Method to parse json result and get the value of the key "image"
private String returnParsedJsonObject(String result){
JSONObject resultObject = null;
String returnedResult = "";
try {
resultObject = new JSONObject(result);
returnedResult = resultObject.getString("image");
} catch (JSONException e) {
e.printStackTrace();
}
return returnedResult;
}
}
class GetBitmapImageFromUrl extends AsyncTask<String,Void,Bitmap>{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Bitmap doInBackground(String... params) {
try {
profilePicBitmap = BitmapFactory.decodeStream((InputStream)new URL(params[0]).getContent());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
}
}
}
If you are seeing background white instead image. Out of memory exception by using bitmap.
You could use
Option 1
URL newurl = new URL(photo_url_str);
mIcon_val = BitmapFactory.decodeStream(newurl.openConnection() .getInputStream());
profile_photo.setImageBitmap(mIcon_val);
Picasso
Picasso.with(context).load("http://www.myegotest.com/PhotoUpload/uploads/5.png").into(profilePicture);
I would suggest to go with Piccasso. Since it will handle everything.
I am developing an app which would talk to the server which is developed using spring. I got to a point where we i was getting data from the google api and wanted to pass it to the spring server. But when i do pass it, the server accepts it but the data is not being stored in the mysql database.
Here is the code I am using:
This is the main spring application + controller:
#EnableJpaRepositories(basePackageClasses = StudentRepository.class)
#SpringBootApplication
public class Demo3Application {
public static void main(String[] args) {
SpringApplication.run(Demo3Application.class, args);
}
}
#RestController
class StudentController
{
#Autowired
public StudentRepository students;
#RequestMapping(value = "/getstudent", method = RequestMethod.GET)
public #ResponseBody List<Student> fetchStudents()
{
if(students.count() == 0)
{
Vector<VideoList> no_video = new Vector<VideoList>();
VideoList no_v = new VideoList("No Videos found", null, null, null);
no_video.add(no_v);
return no_video;
return null;
}
return null;
}
#RequestMapping(value = "/poststudent" , method = RequestMethod.POST)
public #ResponseBody String putStudents(#RequestBody Student v )
{
students.save(v);
return "Student Successfully Added";
}
#RequestMapping(value = "/searchstudent/{str}" , method = RequestMethod.GET)
public #ResponseBody String searchStudent(
#PathVariable("str") String searchQuery
)
{
if(students.existsByEmail(searchQuery)){
List<Student> sList = students.findEmail(searchQuery,new PageRequest(0, 1));
Student s = sList.get(0);
String str = "";
Vector<CourseList> c = s.getCourses();
Iterator<CourseList> it = c.iterator();
while(it.hasNext()){
str.concat(it.next().toString());
str.concat("\n");
}
return str;
}
return null ;
}
#RequestMapping(value = "/addcourse" , method = RequestMethod.POST)
public #ResponseBody String postCourse(#RequestParam String email, #RequestParam String course){
List<Student> sList = students.findEmail(email,new PageRequest(0, 1));
Student s = sList.get(0);
CourseList c = new CourseList();
c.setName(course);
s.addCourse(c);
students.save(s);
return null;
}
}
This is the Student class:
#Entity
#Table(name = "table1")
public class Student {
private String name;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String email;
private Vector<CourseList> courses = new Vector<CourseList>();//CourseList is just a class to store data about various courses.
public Student(){}
public String getName(){
return name;
}
public String getEmail(){
return email;
}
public Vector<CourseList> getCourses(){
return courses;
}
public void setName(String name){
this.name = name;
}
public void setEmail(String email){
this.email = email;
}
public void setCourses(Vector<CourseList> courses){
this.courses = courses;
}
public void addCourse(CourseList c){
courses.add(c);
}
}
This is my repository:
#Repository
#Transactional
public interface StudentRepository extends CrudRepository<Student,String>{
#Query("SELECT s FROM Student s WHERE email = ?1")
public List<Student> findEmail(String searchQuery, Pageable pageable);
#Query("SELECT CASE WHEN COUNT(s) > 0 THEN 'true' ELSE 'false' END FROM Student s WHERE s.email = ?1")
public boolean existsByEmail(String searchQuery);
}
This is my application.properties file:
spring.datasource.url: jdbc:mysql://localhost/mydb
spring.datasource.driverClassName: com.mysql.jdbc.Driver
spring.datasource.username: root
spring.datasource.password:root
# Specify the DBMS
spring.jpa.database = MYSQL
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = update
# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
# Use spring.jpa.properties.* for Hibernate native properties (the prefix is
# stripped before adding them to the entity manager)
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
And finally here is the android code to test the above:
public class MainActivity extends Activity implements OnClickListener,
ConnectionCallbacks, OnConnectionFailedListener {
private static final int RC_SIGN_IN = 0;
// Logcat tag
private static final String TAG = "MainActivity";
// Profile pic image size in pixels
private static final int PROFILE_PIC_SIZE = 400;
// Google client to interact with Google API
private GoogleApiClient mGoogleApiClient;
/**
* A flag indicating that a PendingIntent is in progress and prevents us
* from starting further intents.
*/
private boolean mIntentInProgress;
private boolean mSignInClicked;
private ConnectionResult mConnectionResult;
private SignInButton btnSignIn;
private Button btnSignOut;
private ImageView imgProfilePic;
private TextView txtName, txtEmail, course;
private LinearLayout llProfileLayout;
private Button SC;
private String personName;
private String personPhotoUrl;
private String personGooglePlusProfile;
private String email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSignIn = (SignInButton) findViewById(R.id.btn_sign_in);
btnSignOut = (Button) findViewById(R.id.btn_sign_out);
imgProfilePic = (ImageView) findViewById(R.id.imgProfilePic);
txtName = (TextView) findViewById(R.id.txtName);
course = (TextView) findViewById(R.id.txtCourses);
txtEmail = (TextView) findViewById(R.id.txtEmail);
llProfileLayout = (LinearLayout) findViewById(R.id.llProfile);
SC=(Button)findViewById(R.id.Scourse);
// Button click listeners
btnSignIn.setOnClickListener(this);
btnSignOut.setOnClickListener(this);
SC.setOnClickListener(this);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).addApi(Plus.API)
.addScope(Plus.SCOPE_PLUS_LOGIN).build();
}
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
/**
* Method to resolve any signin errors
* */
private void resolveSignInError() {
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
} catch (SendIntentException e) {
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
if (!result.hasResolution()) {
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this,
0).show();
return;
}
if (!mIntentInProgress) {
// Store the ConnectionResult for later usage
mConnectionResult = result;
if (mSignInClicked) {
// The user has already clicked 'sign-in' so we attempt to
// resolve all
// errors until the user is signed in, or they cancel.
resolveSignInError();
}
}
}
#Override
protected void onActivityResult(int requestCode, int responseCode,
Intent intent) {
if (requestCode == RC_SIGN_IN) {
if (responseCode != RESULT_OK) {
mSignInClicked = false;
}
mIntentInProgress = false;
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
}
}
#Override
public void onConnected(Bundle arg0) {
mSignInClicked = false;
Toast.makeText(this, "User is connected!", Toast.LENGTH_LONG).show();
// Get user's information
getProfileInformation();
// Update the UI after signin
updateUI(true);
}
/**
* Updating the UI, showing/hiding buttons and profile layout
* */
private void updateUI(boolean isSignedIn) {
if (isSignedIn) {
btnSignIn.setVisibility(View.GONE);
btnSignOut.setVisibility(View.VISIBLE);
llProfileLayout.setVisibility(View.VISIBLE);
getCourses();
SC.setVisibility(View.VISIBLE);
} else {
btnSignIn.setVisibility(View.VISIBLE);
btnSignOut.setVisibility(View.GONE);
llProfileLayout.setVisibility(View.GONE);
course.setText(" ");
SC.setVisibility(View.GONE);
}
}
private void getCourses(){
new StudentSearch().execute();
}
private class StudentSearch extends AsyncTask<String, Void, String >
{
String content = "";
#Override
protected String doInBackground(String... urls) {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://192.168.49.8:8080/searchstudent/"+email);
StringBuffer studentString = new StringBuffer();
try {
HttpResponse response = httpClient.execute(httpget);
InputStream responseString = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(responseString));
String res = "";
if ((res = reader.readLine()) == null) {
studentString.append("");
HttpPost httpPost = new HttpPost("http://192.168.49.8:8080/poststudent/");
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("name", personName);
jsonObject.put("email", email);
} catch (JSONException e) {
e.printStackTrace();
}
try {
StringEntity se = new StringEntity(jsonObject.toString());
se.setContentType("application/json;charset=UTF-8");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));
httpPost.setEntity(se);
} catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
}
} else {
studentString.append(res);
studentString.append("\n");
while ((res = reader.readLine()) != null) {
studentString.append(res);
studentString.append("\n");
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
return studentString.toString();
}
#Override
protected void onPostExecute(String s) {
if (!s.isEmpty()){
course.setText("Courses Taken:\n"+s);}
else
course.setText("No Courses Taken!");
}
}
/**
* Fetching user's information name, email, profile pic
* */
private void getProfileInformation() {
try {
if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
Person currentPerson = Plus.PeopleApi
.getCurrentPerson(mGoogleApiClient);
personName = currentPerson.getDisplayName();
personPhotoUrl = currentPerson.getImage().getUrl();
personGooglePlusProfile = currentPerson.getUrl();
email = Plus.AccountApi.getAccountName(mGoogleApiClient);
Log.e(TAG, "Name: " + personName + ", plusProfile: "
+ personGooglePlusProfile + ", email: " + email
+ ", Image: " + personPhotoUrl);
txtName.setText(personName);
txtEmail.setText(email);
// by default the profile url gives 50x50 px image only
// we can replace the value with whatever dimension we want by
// replacing sz=X
personPhotoUrl = personPhotoUrl.substring(0,
personPhotoUrl.length() - 2)
+ PROFILE_PIC_SIZE;
new LoadProfileImage(imgProfilePic).execute(personPhotoUrl);
} else {
Toast.makeText(getApplicationContext(),
"Person information is null", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
updateUI(false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
return true;
}
/**
* Button on click listener
* */
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_sign_in:
// Signin button clicked
signInWithGplus();
break;
case R.id.btn_sign_out:
// Signout button clicked
signOutFromGplus();
break;
case R.id.Scourse:
{
Intent intent=new Intent(MainActivity.this,SelectCourse.class);
startActivity(intent);
break;
}
}
}
/**
* Sign-in into google
* */
private void signInWithGplus() {
if (!mGoogleApiClient.isConnecting()) {
mSignInClicked = true;
resolveSignInError();
}
}
/**
* Sign-out from google
* */
private void signOutFromGplus() {
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
mGoogleApiClient.connect();
updateUI(false);
}
}
/**
* Background Async task to load user profile picture from url
* */
private class LoadProfileImage extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public LoadProfileImage(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
I am a total newbie when it comes to developing spring code and would really appreciate some help.
The following app upload video to Dropbox when it is start, I added finish() in the end of onCreate to exit the app when its completed the uploading, but I got "Unfortunately, DBRoulette has stopped.".
In the Eclipse LogCat:
Activity com.dropbox.android.sample.DBRoulette has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#42a7ee38 that was originally added here
android.view.WindowLeaked: Activity com.dropbox.android.sample.DBRoulette has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#42a7ee38 that was originally added here
I have Progress viewer which may cause the problem but I don't know how to solve it!
What I want to do is closing the app automatically when the uploading completed.
DBRoulette.java
#SuppressLint("SimpleDateFormat")
public class DBRoulette extends Activity {
private static final String TAG = "DBRoulette";
final static private String APP_KEY = "<My APP_KEY>";
final static private String APP_SECRET = "<My APP_SECRET>";
// You don't need to change these, leave them alone.
final static private String ACCOUNT_PREFS_NAME = "prefs";
final static private String ACCESS_KEY_NAME = "ACCESS_KEY";
final static private String ACCESS_SECRET_NAME = "ACCESS_SECRET";
private static final boolean USE_OAUTH1 = false;
DropboxAPI<AndroidAuthSession> mApi;
private boolean mLoggedIn;
// Android widgets
private Button mSubmit;
private RelativeLayout mDisplay;
private Button mGallery;
private ImageView mImage;
private final String PHOTO_DIR = "/Motion/";
#SuppressWarnings("unused")
final static private int NEW_PICTURE = 50;
private String mCameraFileName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
mCameraFileName = savedInstanceState.getString("mCameraFileName");
}
// We create a new AuthSession so that we can use the Dropbox API.
AndroidAuthSession session = buildSession();
mApi = new DropboxAPI<AndroidAuthSession>(session);
// Basic Android widgets
setContentView(R.layout.main);
checkAppKeySetup();
mSubmit = (Button) findViewById(R.id.auth_button);
mSubmit.setOnClickListener(new OnClickListener() {
#SuppressWarnings("deprecation")
public void onClick(View v) {
// This logs you out if you're logged in, or vice versa
if (mLoggedIn) {
logOut();
} else {
// Start the remote authentication
if (USE_OAUTH1) {
mApi.getSession().startAuthentication(DBRoulette.this);
} else {
mApi.getSession().startOAuth2Authentication(
DBRoulette.this);
}
}
}
});
mDisplay = (RelativeLayout) findViewById(R.id.logged_in_display);
// This is where a photo is displayed
mImage = (ImageView) findViewById(R.id.image_view);
File outFile = new File("/mnt/sdcard/ipwebcam_videos/video.mov");
mCameraFileName = outFile.toString();
UploadPicture upload = new UploadPicture(DBRoulette.this, mApi, PHOTO_DIR,outFile);
upload.execute();
// Display the proper UI state if logged in or not
setLoggedIn(mApi.getSession().isLinked());
finish();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putString("mCameraFileName", mCameraFileName);
super.onSaveInstanceState(outState);
}
#Override
protected void onResume() {
super.onResume();
AndroidAuthSession session = mApi.getSession();
if (session.authenticationSuccessful()) {
try {
session.finishAuthentication();
storeAuth(session);
setLoggedIn(true);
} catch (IllegalStateException e) {
showToast("Couldn't authenticate with Dropbox:"
+ e.getLocalizedMessage());
Log.i(TAG, "Error authenticating", e);
}
}
}
private void logOut() {
// Remove credentials from the session
mApi.getSession().unlink();
clearKeys();
// Change UI state to display logged out version
setLoggedIn(false);
}
#SuppressWarnings("deprecation")
public String getRealPathFromURI(Uri contentUri)
{
String[] proj = { MediaStore.Audio.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
private void setLoggedIn(boolean loggedIn) {
mLoggedIn = loggedIn;
if (loggedIn) {
mSubmit.setText("Logout from Dropbox");
mDisplay.setVisibility(View.VISIBLE);
} else {
mSubmit.setText("Login with Dropbox");
mDisplay.setVisibility(View.GONE);
mImage.setImageDrawable(null);
}
}
private void checkAppKeySetup() {
// Check to make sure that we have a valid app key
if (APP_KEY.startsWith("CHANGE") || APP_SECRET.startsWith("CHANGE")) {
showToast("You must apply for an app key and secret from developers.dropbox.com, and add them to the DBRoulette ap before trying it.");
finish();
return;
}
// Check if the app has set up its manifest properly.
Intent testIntent = new Intent(Intent.ACTION_VIEW);
String scheme = "db-" + APP_KEY;
String uri = scheme + "://" + AuthActivity.AUTH_VERSION + "/test";
testIntent.setData(Uri.parse(uri));
PackageManager pm = getPackageManager();
if (0 == pm.queryIntentActivities(testIntent, 0).size()) {
showToast("URL scheme in your app's "
+ "manifest is not set up correctly. You should have a "
+ "com.dropbox.client2.android.AuthActivity with the "
+ "scheme: " + scheme);
finish();
}
}
private void showToast(String msg) {
Toast error = Toast.makeText(this, msg, Toast.LENGTH_LONG);
error.show();
}
/**
* Shows keeping the access keys returned from Trusted Authenticator in a
* local store, rather than storing user name & password, and
* re-authenticating each time (which is not to be done, ever).
*/
private void loadAuth(AndroidAuthSession session) {
SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
String key = prefs.getString(ACCESS_KEY_NAME, null);
String secret = prefs.getString(ACCESS_SECRET_NAME, null);
if (key == null || secret == null || key.length() == 0
|| secret.length() == 0)
return;
if (key.equals("oauth2:")) {
// If the key is set to "oauth2:", then we can assume the token is
// for OAuth 2.
session.setOAuth2AccessToken(secret);
} else {
// Still support using old OAuth 1 tokens.
session.setAccessTokenPair(new AccessTokenPair(key, secret));
}
}
/**
* Shows keeping the access keys returned from Trusted Authenticator in a
* local store, rather than storing user name & password, and
* re-authenticating each time (which is not to be done, ever).
*/
private void storeAuth(AndroidAuthSession session) {
// Store the OAuth 2 access token, if there is one.
String oauth2AccessToken = session.getOAuth2AccessToken();
if (oauth2AccessToken != null) {
SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME,
0);
Editor edit = prefs.edit();
edit.putString(ACCESS_KEY_NAME, "oauth2:");
edit.putString(ACCESS_SECRET_NAME, oauth2AccessToken);
edit.commit();
return;
}
// Store the OAuth 1 access token, if there is one. This is only
// necessary if
// you're still using OAuth 1.
AccessTokenPair oauth1AccessToken = session.getAccessTokenPair();
if (oauth1AccessToken != null) {
SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME,
0);
Editor edit = prefs.edit();
edit.putString(ACCESS_KEY_NAME, oauth1AccessToken.key);
edit.putString(ACCESS_SECRET_NAME, oauth1AccessToken.secret);
edit.commit();
return;
}
}
private void clearKeys() {
SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
Editor edit = prefs.edit();
edit.clear();
edit.commit();
}
private AndroidAuthSession buildSession() {
AppKeyPair appKeyPair = new AppKeyPair(APP_KEY, APP_SECRET);
AndroidAuthSession session = new AndroidAuthSession(appKeyPair);
loadAuth(session);
return session;
}
}
UploadPicture.java
public class UploadPicture extends AsyncTask<Void, Long, Boolean> {
private DropboxAPI<?> mApi;
private String mPath;
private File mFile;
private long mFileLen;
private UploadRequest mRequest;
private Context mContext;
private final ProgressDialog mDialog;
private String mErrorMsg;
private File outFiles;
public UploadPicture(Context context, DropboxAPI<?> api, String dropboxPath,
File file) {
// We set the context this way so we don't accidentally leak activities
mContext = context.getApplicationContext();
mFileLen = file.length();
mApi = api;
mPath = dropboxPath;
mFile = file;
Date dates = new Date();
DateFormat dfs = new SimpleDateFormat("yyyyMMdd-kkmmss");
String newPicFiles = dfs.format(dates) + ".mov";
String outPaths = new File(Environment
.getExternalStorageDirectory(), newPicFiles).getPath();
outFiles = new File(outPaths);
mDialog = new ProgressDialog(context);
mDialog.setMax(100);
mDialog.setMessage("Uploading " + outFiles.getName());
mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mDialog.setProgress(0);
mDialog.setButton(ProgressDialog.BUTTON_POSITIVE, "Cancel", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// This will cancel the putFile operation
mRequest.abort();
}
});
mDialog.show();
}
#Override
protected Boolean doInBackground(Void... params) {
try {
// By creating a request, we get a handle to the putFile operation,
// so we can cancel it later if we want to
FileInputStream fis = new FileInputStream(mFile);
String path = mPath + outFiles.getName();
mRequest = mApi.putFileOverwriteRequest(path, fis, mFile.length(),
new ProgressListener() {
#Override
public long progressInterval() {
// Update the progress bar every half-second or so
return 500;
}
#Override
public void onProgress(long bytes, long total) {
publishProgress(bytes);
}
});
if (mRequest != null) {
mRequest.upload();
return true;
}
} catch (DropboxUnlinkedException e) {
// This session wasn't authenticated properly or user unlinked
mErrorMsg = "This app wasn't authenticated properly.";
} catch (DropboxFileSizeException e) {
// File size too big to upload via the API
mErrorMsg = "This file is too big to upload";
} catch (DropboxPartialFileException e) {
// We canceled the operation
mErrorMsg = "Upload canceled";
} catch (DropboxServerException e) {
// Server-side exception. These are examples of what could happen,
// but we don't do anything special with them here.
if (e.error == DropboxServerException._401_UNAUTHORIZED) {
// Unauthorized, so we should unlink them. You may want to
// automatically log the user out in this case.
} else if (e.error == DropboxServerException._403_FORBIDDEN) {
// Not allowed to access this
} else if (e.error == DropboxServerException._404_NOT_FOUND) {
// path not found (or if it was the thumbnail, can't be
// thumbnailed)
} else if (e.error == DropboxServerException._507_INSUFFICIENT_STORAGE) {
// user is over quota
} else {
// Something else
}
// This gets the Dropbox error, translated into the user's language
mErrorMsg = e.body.userError;
if (mErrorMsg == null) {
mErrorMsg = e.body.error;
}
} catch (DropboxIOException e) {
// Happens all the time, probably want to retry automatically.
mErrorMsg = "Network error. Try again.";
} catch (DropboxParseException e) {
// Probably due to Dropbox server restarting, should retry
mErrorMsg = "Dropbox error. Try again.";
} catch (DropboxException e) {
// Unknown error
mErrorMsg = "Unknown error. Try again.";
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return false;
}
#Override
protected void onProgressUpdate(Long... progress) {
int percent = (int)(100.0*(double)progress[0]/mFileLen + 0.5);
mDialog.setProgress(percent);
}
#Override
protected void onPostExecute(Boolean result) {
mDialog.dismiss();
if (result) {
showToast("Image successfully uploaded");
} else {
showToast(mErrorMsg);
}
}
private void showToast(String msg) {
Toast error = Toast.makeText(mContext, msg, Toast.LENGTH_LONG);
error.show();
}
}
Your problem is that you are trying to update an Activity's UI after the activity has finished.
First, you kick of an AsyncTask which posts progress updates to the UI thread. Then, before the task completes, you call finish(). Any updates to the Activity's UI after finish() is called are liable to throw exceptions, cause window leak issues, etc.
If you want to have any UI behavior as you perform your AsyncTask, you do not want to finish() the Activity until it the task is completed.
To achieve this, you could include a callback in the onPostExecute which tells the activity it is OK to finish once the AsyncTask completes.
This is how I would do it:
Change the signature of UploadPicture:
final Activity callingActivity;
public UploadPicture(final Activity callingActivity, DropboxAPI api, String dropboxPath, File file) {
Context mContext = callingActivity.getApplicationContext();
this.callingActivity = callingActivity;
Add the finish call to onPostExecute:
#Override
protected void onPostExecute(Boolean result) {
mDialog.dismiss();
if (result) {
showToast("Image successfully uploaded");
} else {
showToast(mErrorMsg);
}
callingActivity.finish(); //Finish activity only once you are done
}
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
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.