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
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.
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 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 an activity that creates an AsyncTask to test an ftp connection via an FTPHelper class. The Activity shows a Toast with the boolean status of the connection, either success or fail. How can I show the exact replycode or replystring in the Activity?
Activity:
TestConnection task = new TestConnection(NewSite.this,
_address, _user, _pass, p, new testConnInterface() {
#Override
public void testConnection(boolean result) {
if (result == true) {
Toast.makeText(NewSite.this,
"Connection Succesful",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(NewSite.this,
"Connection Failed:" + result,
Toast.LENGTH_LONG).show();
}
}
});
task.execute();
TestConection.java
public class TestConnection extends AsyncTask<Void, Void, Boolean> {
private Context mContext;
private testConnInterface mListener;
private FTPHelper ftpHelper = new FTPHelper();
private String _address;
private String _user;
private String _pass;
private int _port;
ProgressDialog progressDialog;
public interface testConnInterface {
public void testConnection(boolean result);
}
public TestConnection(Context context, String address, String user,
String pass, int port, testConnInterface mListener) {
mContext = context;
_address = address;
_user = user;
_pass = pass;
_port = port;
this.mListener = mListener;
}
// declare other objects as per your need
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(mContext, "Please wait",
"Attempting to connect", true);
// do initialization of required objects objects here
};
#Override
protected Boolean doInBackground(Void... params) {
boolean status = ftpHelper.ftpConnect(_address, _user, _pass, _port);
return status;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if (mListener != null)
mListener.testConnection(result);
progressDialog.dismiss();
};
}
FTPHelper.java
public class FTPHelper {
public static FTPClient mFTPClient = null;
public FTPHelper() {
// TODO Auto-generated constructor stub
}
public boolean ftpConnect(String host, String username, String password,
int port) {
try {
mFTPClient = new FTPClient();
// connecting to the host
mFTPClient.connect(host, port);
// now check the reply code, if positive mean connection success
if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
// login using username & password
boolean status = mFTPClient.login(username, password);
/*
* Set File Transfer Mode
*
* To avoid corruption issue you must specified a correct
* transfer mode, such as ASCII_FILE_TYPE, BINARY_FILE_TYPE,
* EBCDIC_FILE_TYPE .etc. Here, I use BINARY_FILE_TYPE for
* transferring text, image, and compressed files.
*/
mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
mFTPClient.enterLocalPassiveMode();
showServerReply(mFTPClient);
return status;
}
} catch (Exception e) {
// Log.d(TAG, "Error: could not connect to host " + host );
}
return false;
}
public boolean ftpDisconnect() {
try {
mFTPClient.logout();
mFTPClient.disconnect();
return true;
} catch (Exception e) {
// Log.d(TAG,
// "Error occurred while disconnecting from ftp server.");
}
return false;
}
public String ftpGetCurrentWorkingDirectory() {
try {
String workingDir = mFTPClient.printWorkingDirectory();
return workingDir;
} catch (Exception e) {
Log.i("Error working dir", e.toString());
}
return null;
}
Basically I want to know how to return the getReplyCode() to my Activity.
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.