I have a file that is supposed to pull a list of products from my MySQL database, encode them into a JSON array then I need to make the Android application display those.
Ideally I want it to display icons but that's something I can tinker with later for now I just want to get it to work
Using the current code below when I click the button it doesn't do anything. My LogCat shows my JSON perfectly fine but the app doesn't display anything, or crash.
public class GetProducts extends Activity {
//Delcare Variables
// JSON Response node names
private static String KEY_SUCCESS = "success";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.view_products);
Functions userFunctions = new Functions();
if(!userFunctions.isConnected(getApplicationContext()))
{
displayDialogue("Connection Error","Your network settings are invalid - please turn on network settings ", "Open Network Settings");
}
if(!userFunctions.isUserLoggedIn(getApplicationContext())){
Intent i = new Intent(GetProducts.this, FirstScreen.class);
startActivity(i);
}
Button btnLogin;
btnLogin = (Button)findViewById(R.id.btnGetProducts);
//When our login button is pressed
btnLogin.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new LoginTask().execute();
}
});
//Assign the variables our layout buttons
}
//We are using an AsyncTask so that this function runs on a seperate thread of the processor
//Since 4.2 + Android requires any web or HTTP activity to be ran seperate thread to the GUI
class LoginTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
//Run the login function
Login();
return null;
}
}
public void displayDialogue(String title, String Message, String Button){
final AlertDialog.Builder myDialogue = new AlertDialog.Builder(this);
myDialogue.setTitle(title);
myDialogue.setMessage(Message);
TextView messageView = new TextView(this);
messageView.setGravity(Gravity.CENTER);
myDialogue.setView(messageView);
myDialogue.setCancelable(false);
myDialogue.setPositiveButton(Button, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog = myDialogue.create();
dialog.show();
}
public void Login(){
try{
Functions userFunctions = new Functions();
final JSONObject json = userFunctions.getProducts();
JSONObject json_user = json.getJSONObject("products");
JSONArray jArray;
jArray = json.getJSONArray("products");
if (json.getString("success") != null) {
String res = json.getString("success");
if(Integer.parseInt(res) == 1){
try{
// user successfully logged in
// Store user details in SQLite Database
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
displayDialogue("Error",json.getString("name"), "Try Again");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
// Clear all previous data in database
// Close Login Screen
finish();
}
catch(final Exception e){
runOnUiThread(new Runnable() {
#Override
public void run() {
displayDialogue("Error",e.toString(), "Try Again");
}
});
}
}
else{
runOnUiThread(new Runnable() {
#Override
public void run() {
displayDialogue("Error", "Error. \nWrong username / password combination please re-enter the details", "Try Again");
}
});
}
}else{
runOnUiThread(new Runnable() {
#Override
public void run() {
displayDialogue("Error", "Error. \nGeneric Error", "Try Again");
}
});
}
}
catch(JSONException e){
e.printStackTrace();
}
}
}
JSON result:- (Printed to Logcat)
12-27 16:53:45.011: E/JSON(23028): {"tag":"getProducts","success":1,"error":0,"products":{"name":"Coffee1","price":"4.00","image":"http:\/\/test.com"}}{"tag":"getProducts","success":1,"error":0,"products":{"name":"Coffee2","price":"5.00","image":"http:\/\/test2.com"}}
Any help would be great, thanks!
Related
i made an app using java language, Retrofit2 and REST API for server side. in me API class i have login and register parameters like
public interface ApiInterface {
#FormUrlEncoded
#POST("/login")
void login(#Field("email") String email, #Field("password") String password, Callback<LoginResult> cb);
public static class LoginResult
{
public int status;
public String user_api_hash;
}
#GET("/registration_status")
void registrationStatus(#Query("lang") String lang, Callback<RegistrationStatusResult> cb);
public static class RegistrationStatusResult
{
public int status;
}
#GET("/get_user_data")
void getMyAccountData(#Query("user_api_hash") String user_api_hash, #Query("lang") String lang, Callback<GetMyAccountDataResult> cb);
public static class GetMyAccountDataResult
{
public String email, expiration_date, plan;
public int days_left, devices_limit;
}
my login class is working properly i can login and register any time. when logged in i receive api_kay then it's saved and use in all the app for requests DataSaver.getInstance(LoginActivity.this).save("api_key", loginResult.user_api_hash); my loginActivity looks like :
public class LoginActivity extends AppCompatActivity {
private static final String TAG = "EditObjectActivity";
#Bind(R.id.username)
EditText username;
#Bind(R.id.password)
EditText password;
#Bind(R.id.signin)
Button signin;
#Bind(R.id.register)
Button pwreset;
private String UrlPrefix;
private String customServerAddress="https://voila_voila_mon_url.com/";
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if(activeNetwork == null) {
Intent intent = new Intent(LoginActivity.this, NoInternetActivity.class);
startActivity(intent);
}
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_WIFI_STATE}, PackageManager.PERMISSION_GRANTED);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.INTERNET}, PackageManager.PERMISSION_GRANTED);
progressDialog = new ProgressDialog(this);
signin = (Button) findViewById(R.id.signin);
pwreset = (Button) findViewById(R.id.register);
password = findViewById(R.id.password);
username = findViewById(R.id.username);
String ip = getResources().getString(R.string.ip);
String httpsOn = getResources().getString(R.string.https_on);
String server_base = customServerAddress;
DataSaver.getInstance(LoginActivity.this).save("server_base", server_base);
DataSaver.getInstance(LoginActivity.this).save("server", server_base + "api/");
if (ip.isEmpty()) {
enableRegistration();
}
else {
API.getApiInterface(LoginActivity.this).registrationStatus("en", new Callback<ApiInterface.RegistrationStatusResult>()
{
#Override
public void success(ApiInterface.RegistrationStatusResult result, Response response)
{
if (result.status == 1) {
enableRegistration();
}
}
#Override
public void failure(RetrofitError retrofitError) {
Log.e(TAG, "failure: retrofitError" + retrofitError.getMessage());
Toast.makeText(LoginActivity.this, getString(R.string.errorHappened), Toast.LENGTH_SHORT).show();
}
});
}
signin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(customServerAddress != null) {
String server_base = customServerAddress;
server_base = UrlPrefix + server_base;
DataSaver.getInstance(LoginActivity.this).save("server_base", server_base);
DataSaver.getInstance(LoginActivity.this).save("server", server_base + "api/");
}
API.getApiInterface(LoginActivity.this).login(username.getText().toString(), password.getText().toString(), new Callback<ApiInterface.LoginResult>()
{
#Override
public void success(ApiInterface.LoginResult loginResult, Response response)
{ // progress dialogue
progressDialog = new ProgressDialog(LoginActivity.this);
progressDialog.setMessage("En cours..."); // Setting Message
progressDialog.setTitle("Connexion au serveur"); // Setting Title
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); // Progress Dialog Style Spinner
progressDialog.show(); // Display Progress Dialog
progressDialog.setCancelable(false);
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(10000);
} catch (Exception e) {
e.printStackTrace();
}
progressDialog.dismiss();
}
}).start();
//end progress dialogue
DataSaver.getInstance(LoginActivity.this).save("api_key", loginResult.user_api_hash);
Log.d("LoginActivity", "api_key: " + loginResult.user_api_hash);
if(customServerAddress == null)
{
String url = "https://voila_voila_mon_url.com/";
DataSaver.getInstance(LoginActivity.this).save("server_base", url);
DataSaver.getInstance(LoginActivity.this).save("server", url + "api/");
}
Intent intent = new Intent(LoginActivity.this, MapActivity.class);
startActivity(intent);
finish();
}
#Override
public void failure(RetrofitError retrofitError)
{
Toast.makeText(LoginActivity.this, getString(R.string.wrongLogin), Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
now the thing is i'd look to log out in my mean activity. in my reseachs i have been told that once logged out the api_key in DataSaver.getInstance(LoginActivity.this).save("api_key", loginResult.user_api_hash); should be null like api_key =null.also when i open the app it show that i am logged. i want to log out.here is my example on my_logout button i did this :
disconnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String log_out = null;
if(DataSaver.getInstance(this).load("api_key") != null){
DataSaver.getInstance(this).load("api_key") == log_out;
finish();
}else{
//Toast.......(Toast with message ->>>>unable to log out).
}
});
This DataSaver.getInstance(this).load("api_key") is used in all the app when requesting for GET method when fetching users datas. the api_key saved in the app allow me to make some requests as said before. but when this is null it's impossible to make requests. i want to destroy the session when logged in by loggin out. if you understand what i say and can help please.
my account activity after logged in
public class MyAccountActivity extends AppCompatActivity
{
#Bind(R.id.back) View back;
#Bind(R.id.expandable_list) ExpandableListView expandable_list;
#Bind(R.id.loading_layout) View loading_layout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_account);
ButterKnife.bind(this);
loading_layout.setVisibility(View.VISIBLE);
API.getApiInterface(this).getMyAccountData((String) DataSaver.getInstance(this).load("api_key"), getResources().getString(R.string.lang), new Callback<ApiInterface.GetMyAccountDataResult>() {
#Override
public void success(ApiInterface.GetMyAccountDataResult dataResult, Response response)
{
MyAccountAdapter adapter = new MyAccountAdapter(MyAccountActivity.this, dataResult);
expandable_list.setAdapter(adapter);
Utils.setGroupClickListenerToNotify(expandable_list, adapter);
loading_layout.setVisibility(View.GONE);
expandable_list.setVisibility(View.VISIBLE);
}
#Override
public void failure(RetrofitError retrofitError) {
Toast.makeText(MyAccountActivity.this, R.string.errorHappened, Toast.LENGTH_SHORT).show();
}
});
}
i did this but it's not enough to log out #Syed Ibrahim
like this
but not working this is juste to stay connected not to log out
if (DataSaver.getInstance(this).load("api_key") == null)
{
startActivity(new Intent(MapActivity.this, LoginActivity.class));
finish();
return;
}
what i need is to set this api_key null whatever the app is running or not.
I am using Twitter 4j to post tweet on single button. If user revoke access of my app then its showing Error in Logcat in do in background i want this error and if this error comes my another hide button of twitter authorize app visible. how do i do that please help. I need that error and if its exists i want to hide show my buttons.
class updateTwitterStatus extends AsyncTask<String, String, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected Void doInBackground(String... args) {
String status = args[0];
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(consumerKey);
builder.setOAuthConsumerSecret(consumerSecret);
String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");
AccessToken accessToken = new AccessToken(access_token, access_token_secret);
twitter4j.Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
StatusUpdate statusUpdate = new StatusUpdate(status);
File extStore = Environment.getExternalStoragePublicDirectory("/Twitter/Cache/demo.jpg");
statusUpdate.setMedia(extStore);
twitter4j.Status response = twitter.updateStatus(statusUpdate);
} catch (TwitterException e) {
Log.d("Failed to post!", e.getMessage());
error=e; //error is exception
}
return null;}
#Override
protected void onPostExecute(Void result) {
pDialog.dismiss();
Toast.makeText(getContext(), "Posted to Twitter!"+error, Toast.LENGTH_SHORT).show();
/* i need a variable like int a =10; access it globally, How i do that/*
} } }
You can save the exception in a variable and check it in onPostExecute()
and hide your button ..
new AsyncTask<Void, Void, Boolean>() {
Exception error;
#Override
protected Boolean doInBackground(Void... params) {
try {
// do work
return true;
} catch (Exception e) {
error = e;
return false;
}
}
#Override
protected void onPostExecute(Boolean result) {
if (result) {
Toast.makeText(ctx, "Success!",
Toast.LENGTH_SHORT).show();
} else {
if (error != null) {
Toast.makeText(getApplicationContext(), error.getMessage(),
Toast.LENGTH_SHORT).show();
//error occurs hide button here
}
}
}
}
Hi in the below code when clicking the report button not going to login activity even though it's not happening anything.
In login activity first of all I am checking the login username and password using session object.
if the username and password working fine and then want to move to next activity.
Can any one help me from this issue.
Mainactivity.java
report1=(TextView)findViewById(R.id.report1);
report=(ImageView)findViewById(R.id.report);
report1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),Login.class);
startActivity(i);
}
});
report.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),Login.class);
startActivity(i);
}
});
In the below when I am putting comment for session then it's moving but after entering the username and password it was showing logcat Admin user found but not going to next activity.it was staying in same activity itself.
update Login
public class Login extends Activity {
ImageButton login;
private static final Pattern USERNAME_PATTERN = Pattern
.compile("[a-zA-Z0-9]{1,250}");
private static final Pattern PASSWORD_PATTERN = Pattern
.compile("[a-zA-Z0-9+_.]{4,16}");
EditText usname,pword,ustype;
TextView tv,tv1;
Boolean isInternetPresent = false;
String username,password;
HttpPost httppost;
StringBuffer buffer;
String queryString;
String data="";
int i;
HttpResponse response;
HttpClient httpclient;
CheckBox mCbShowPwd;
SessionManager session;
private ProgressDialog progressDialog;
ConnectionDetector cd;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.login);
// session = new SessionManager(getApplicationContext());
// session.checkLogin();
// final HashMap<String, String> user = session.getUserDetails();
login = (ImageButton)findViewById(R.id.login);
usname = (EditText)findViewById(R.id.username);
pword= (EditText)findViewById(R.id.password);
ustype= (EditText)findViewById(R.id.usertype);
tv = (TextView)findViewById(R.id.tv);
tv1 = (TextView)findViewById(R.id.tv1);
mCbShowPwd = (CheckBox) findViewById(R.id.cbShowPwd);
cd = new ConnectionDetector(getApplicationContext());
mCbShowPwd.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (!isChecked) {
pword.setTransformationMethod(PasswordTransformationMethod.getInstance());
} else {
pword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
}
}
});
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new LoadViewTask().execute();
isInternetPresent = cd.isConnectingToInternet();
if (!isInternetPresent) {
showAlertDialog(Login.this, "No Internet Connection",
"You don't have internet connection.", true);
return;
}
String username = usname.getText().toString();
String password = pword.getText().toString();
// String name = user.get(SessionManager.KEY_USERNAME);
if (username.equals("")) {
Toast.makeText(Login.this, "ENTER USERNAME",
Toast.LENGTH_LONG).show();
}
if (password.equals("")) {
Toast.makeText(Login.this, "ENTER PASSWORD",
Toast.LENGTH_LONG).show();
}
else if (!CheckUsername(username) && !CheckPassword(password)){
Toast.makeText(Login.this, "ENTER VALID USERNAME & PASSWORD",
Toast.LENGTH_LONG).show();
}
else{
queryString = "username=" + username + "&password="
+ password ;
String usertype = DatabaseUtility.executeQueryPhp("login",queryString);
System.out.print(usertype);
if(usertype.equalsIgnoreCase("Admin user Found")){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(Login.this, "Login Sucess",
Toast.LENGTH_LONG).show();
}
});
Intent in=new Intent(Login.this, Reports.class);
startActivity(in);
}
else if(usertype.equalsIgnoreCase("No User Found")){
runOnUiThread(new Runnable() {
public void run() {
tv1.setText("InValid UserName and Password");
}
});
}
}
}
});
}
private class LoadViewTask extends AsyncTask<Void, Integer, Void>
{
//Before running code in separate thread
#Override
protected void onPreExecute()
{
progressDialog = ProgressDialog.show(Login.this,"Loading...",
"Loading application View, please wait...", false, false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params)
{
try
{
synchronized (this)
{
int counter = 0;
while(counter <= 4)
{
this.wait(850);
counter++;
publishProgress(counter*25);
}
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values)
{
progressDialog.setProgress(values[0]);
}
#Override
protected void onPostExecute(Void result)
{
progressDialog.dismiss();
}
}
private boolean CheckPassword(String password) {
return PASSWORD_PATTERN.matcher(password).matches();
}
private boolean CheckUsername(String username) {
return USERNAME_PATTERN.matcher(username).matches();
}
#SuppressWarnings("deprecation")
public void showAlertDialog(Context context, String title, String message, Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
}
Do not use the application's context, use the context the view currently be presented.
report.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(v.getContext(), Login.class);
startActivity(i);
}
});
I am attempting to use the android built in login view and parse together.
code
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
try {
// Simulate network access.
Thread.sleep(2000);
} catch (InterruptedException e) {
return false;
}
for (String credential : DUMMY_CREDENTIALS) {
String[] pieces = credential.split(":");
if (pieces[0].equals(mEmail)) {
// Account exists, return true if the password matches.
return pieces[1].equals(mPassword);
}
}
// TODO: register the new account here.
ParseUser newUser = new ParseUser();
newUser.setEmail(mEmail);
newUser.setPassword(mPassword);
newUser.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
// Success!
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
} else {
// Oops!
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setMessage(e.getMessage().toUpperCase())
.setTitle("Oops!")
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
return true;
}
When I run it, I type in my email / password and the application fails.
Have look at this code:
public class LoginActivity extends PlanndActivity
{
public EditText emailField;
public EditText passwordField;
public Button loginButton;
public View.OnClickListener loginButtonListener;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
PushService.setDefaultPushCallback(getApplicationContext(), PlanndActivity.class);
ParseInstallation.getCurrentInstallation().saveInBackground(
new SaveCallback() {
#Override
public void done(ParseException e) {
if(e!= null)
Log.e(Constants.TAG, "ERROR adding callback", e);
}
}
);
emailField = (EditText) findViewById(R.id.email_login);
passwordField = (EditText) findViewById(R.id.password_login);
loginButton = (Button) findViewById(R.id.login_button);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loginButton.setEnabled(false);
String email = ((EditText) findViewById(R.id.email_login)).getText().toString().trim();
String password = ((EditText) findViewById(R.id.password_login)).getText().toString().trim();
ParseUser.logInInBackground(email, password, new LogInCallback() {
#Override
public void done(ParseUser parseUser, ParseException e) {
if(parseUser != null)
{
// User is valid and is now logged in
Log.i(Constants.TAG, "Successful login for user " + parseUser.getUsername());
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
PushService.subscribe(getApplicationContext(), "user_" + ParseUser.getCurrentUser().getObjectId(), PlanndActivity.class);
}
else
{
loginButton.setEnabled(true);
Log.i(Constants.TAG, "Unsuccessful login for user");
// sign up failed and the problems
// needs to go and do the sign up activity
}
}
});
}
});
((Button)findViewById(R.id.register_button)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), RegisterActivity.class));
}
});
((Button)findViewById(R.id.fake_login)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
emailField.setText("rberidon#gmail.com");
passwordField.setText("test");
}
});
}
}
Source: plannd
Try implement this with animation of view like use inline progress bar when user clicks sign in, switch the content and progress bar depending on your logic!
The problem is that your are executing signUpInBackground() inside AsyncTask.doInBackground(). doInBackground is already using a background thread. Just use newUser.signUp()
Below is my code and I integrated the facebook in my app. I am trying to make the user to be able to post an image on his wall after logging in. But I have been failing to make it for three days. Have seen few posts like this but I don't get any data(just it results in empty data data[]). I am even facing trouble with maintaining sessions too. Can some one please post working code or at least some sources where I can post image on facebook wall? Hope my below code is clear and my explanation is clear on what I have tried with the code below.
Activity's onCreate():-
public class FacebookActivity extends BaseActivity {
private static String APP_ID = "1303786178";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fb_screen);
btnFbLogin = (Button) findViewById(R.id.fbloginbtn);
btnFbLogout = (Button) findViewById(R.id.fblogoutbtn);
btnPostToWall = (Button) findViewById(R.id.fbpostbtn);
msget = (EditText)findViewById(R.id.fbmsget);
mAsyncRunner = new AsyncFacebookRunner(facebook);
mHandler = new Handler();
String passedpath = getIntent().getStringExtra("imagepath").toString();
imageuri = Uri.parse(passedpath);
/**
* Login button Click event
* */
btnFbLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Image Button", "button Clicked");
loginToFacebook();
}
});
btnFbLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Image Button", "button Clicked");
logoutFromFacebook();
}
});
/**
* Posting to Facebook Wall
* */
btnPostToWall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//postToWall(imageuri);
getAlbumId();
}
});
}
Posting on Wall includes two functions in my code one is getAlbumId() and the other is posttowall() which will be called from getAlbumId():-
public void getAlbumId()
{
dialog = ProgressDialog.show(FacebookActivity.this, "","Please Wait...", true, true);
//String wallAlbumID = null;
mAsyncRunner.request("me/albums", new BaseRequestListener(){
#Override
public void onComplete(String response, Object state) {
// TODO Auto-generated method stub
try{
Log.d("response in album"," "+response);
JSONObject json = Util.parseJson(response);
JSONArray albums = json.getJSONArray("data");
for (int i =0; i < albums.length(); i++) {
JSONObject album = albums.getJSONObject(i);
if (album.getString("type").equalsIgnoreCase("wall")) {
final String wallAlbumID = album.getString("id");
globalalbid = wallAlbumID;
Log.d("JSON", wallAlbumID);
break;
}
}
dialog.dismiss();
mHandler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "id: " + globalalbid, Toast.LENGTH_LONG).show();
if(globalalbid != "")
postToWall(imageuri, globalalbid);
}
});
}catch (JSONException e) {
e.printStackTrace();
}
}
});
}
function to post on wall:
public void postToWall(Uri locuri, String wallid) {
if (facebook.isSessionValid()) {
Util.showAlert(this, "Warning", "You must first log in.");
} else {
dialog = ProgressDialog.show(FacebookActivity.this, "","Please Wait...", true, true);
// post on user's wall.
Uri photoUri = locuri;
if (photoUri != null) {
Bundle params = new Bundle();
try {
params.putByteArray("photo",
Utility.scaleImage(getApplicationContext(), photoUri));
} catch (IOException e) {
e.printStackTrace();
}
String imagecaption = msget.getText().toString();
if(imagecaption != "")
params.putString("caption", imagecaption);
mAsyncRunner.request(wallid+"/photos", params, "POST", new PhotoUploadListener(), null);
} else {
Toast.makeText(getApplicationContext(),
"Error from the pic", Toast.LENGTH_SHORT)
.show();
}
}
}
}
I always get album id empty. Is there anything wrong in the way that I try to get album id. Because I have seen on some posts those who try to access album id and then posting the image on album. They seem to be keeping wall as common findout in the album name. If it is so, some new ones contain timeline photos name, then how can we findout the album id. Please suggest.
Note: I want the image to be visible on to the wall not to only album.
Instead of uploading the photo to the user's album, post the image to /me/feed instead. Make sure you are asking the user for the publish_stream permission. This will upload the photo straight to the user's wall instead of going to an album.