How to save a variable in AsyncTask in Android - android

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
}
}
}
}

Related

Android twitter tweet with images

I am integrating twitter first time in my android application, i am able to post tweet,i want to share image from app,i have URL of images(Which is stored at AmazonS3 server).i want to share this image from my android app ..please anyone can provide steps to achieve this
public class TwitterIntegration extends GlobalActivity {
TwitterAuthClient mTwitterAuthClient;
TwitterApiClient twitterApiClient;
Preferences preferences;
UserHistory userHistory;
StatusesService statusesService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
preferences=HWUtil.getPreferences(this);
userHistory=preferences.getUserHistory();
mTwitterAuthClient=new TwitterAuthClient();
mTwitterAuthClient.authorize(this, new Callback<TwitterSession>() {
#Override
public void success(Result<TwitterSession> result) {
TwitterSession session = result.data;
Log.d("user", session.getUserName());
Log.d("user", session.toString());
HWUtil.showToast(TwitterIntegration.this, session.getUserName());
twitterApiClient = TwitterCore.getInstance().getApiClient(session);
statusesService = twitterApiClient.getStatusesService();
statusesService.update("Hii from android", null, null, null, null,
null, null, null, new Callback<Tweet>() {
#Override
public void success(Result<Tweet> result) {
HWUtil.showToast(TwitterIntegration.this, "Posted SucessFully");
if(Validator.isNotNull(userHistory.getHistoryPictures())&& userHistory.getHistoryPictures().length>0){
shareImage();
}
}
public void failure(TwitterException exception) {
HWUtil.showToast(TwitterIntegration.this, "Failed to post");
}
});
}
#Override
public void failure(TwitterException exception) {
HWUtil.showToast(TwitterIntegration.this, exception.getMessage());
}
});
}
private void shareImage() {
if(Validator.isNotNull(twitterApiClient)){
MediaService mediaService=twitterApiClient.getMediaService();
}
}
#Override
protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
// Pass the activity result to the login button.
super.onActivityResult(requestCode,responseCode,intent);
mTwitterAuthClient.onActivityResult(requestCode, responseCode, intent);
}
}
first of all we have to download all the images as said by #amit i used asynctask
public class DownLoadImageAsyncTask extends AsyncTask{
#Override
protected void onPreExecute() {
progressDialog=new ProgressDialog(TwitterIntegration.this);
progressDialog.setCancelable(false);
progressDialog.setMessage(getString(R.string.please_wait));
progressDialog.setIndeterminate(true);
if(Validator.isNotNull(preferences.getImagePath())&& !preferences.getImagePath().isEmpty()){
preferences.getImagePath().clear();
}
filePath=preferences.getImagePath();
}
#Override
protected Object doInBackground(Object[] params) {
File file=new File(Environment.getExternalStorageDirectory(),"/HealthWel");
if(file.exists()==true){
file.delete();
}
file.mkdir();
for (int i=0;i<mURLs.size();i++){
File f=new File(file+"/"+i+".jpg");
if(f.exists()==true){
f.delete();
}
if(f.exists()==false){
HttpClient httpClient=new DefaultHttpClient();
HttpGet httpGet=new HttpGet(mURLs.get(i));
try {
HttpResponse httpResponse=httpClient.execute(httpGet);
if(httpResponse.getStatusLine().getStatusCode()==200){
HttpEntity httpEntity=httpResponse.getEntity();
InputStream is=httpEntity.getContent();
Boolean status=f.createNewFile();
FileOutputStream fileOutputStream=new FileOutputStream(f);
byte[]buffer=new byte[1024];
long total=0;
int count;
while ((count=is.read(buffer))!=-1){
total+=count;
fileOutputStream.write(buffer,0,count);
}
if(!downLoad) {
if (Validator.isNotNull(preferences.getImagePath()) && !preferences.getImagePath().isEmpty()) {
preferences.getImagePath().clear();
}
}
filePath.add(f.getPath());
fileOutputStream.close();
is.close();
runOnUiThread(new Runnable() {
public void run() {
// runs on UI thread
progressDialog.show();
}
});
}
else {
finish();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Object o) {
preferences.setImagePath(filePath);
dismissProgressDialog();
shareImage();
}
}
private void showProgressDialog() {
if(!isFinishing() && progressDialog==null) {
progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
progressDialog.show();
}
}
/**
* dismiss Progress Dialog.
*/
private void dismissProgressDialog() {
if (!isFinishing() &&progressDialog!=null && progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog=null;
}
}
then we have to upload it to twitter using rest api to get media id using status service and after thatwe have to post it along with status with all media id as post. this perfectly works for me.

Firebase auth with email and password NPE

In 10% of the cases there is a null pointer exception when trying to log in with the email and password authentication with Firebase. This only happens in the release apk. It doesn't occur in the debug app. It says it can't pass null for email. But the email is filled in. And otherwise Firebase sents an error code, but not a npe.
This is the error message:
Caused by: java.lang.NullPointerException: Can't pass null for argument 'email' in authWithPassword()
at com.firebase.client.Firebase.authWithPassword(Unknown Source)
at com.example.verdienapp.ui.start.StartActivity$LoginTask.doInBackground(Unknown Source)
at com.example.verdienapp.ui.start.StartActivity$LoginTask.doInBackground(Unknown Source)
My apologies. I should have directly added my code.
First validating the input:
private void validate() {
this.mEmailEditText.setError(null);
this.mPasswordEditText.setError(null);
String email = this.mEmailEditText.getText().toString();
String password = this.mPasswordEditText.getText().toString();
boolean cancel = false;
View focusView = null;
if (TextUtils.isEmpty(password)) {
this.mPasswordEditText.setError(getString(R.string.error_field_required));
focusView = this.mPasswordEditText;
cancel = true;
} else if (password.length() < 6) {
this.mPasswordEditText.setError(getString(R.string.error_invalid_password));
focusView = this.mPasswordEditText;
cancel = true;
}
if (TextUtils.isEmpty(email)) {
this.mEmailEditText.setError(getString(R.string.error_field_required));
focusView = this.mEmailEditText;
cancel = true;
} else if (!email.contains("#")) {
this.mEmailEditText.setError(getString(R.string.error_invalid_email));
focusView = this.mEmailEditText;
cancel = true;
}
if (cancel) {
if (focusView != null) {
focusView.requestFocus();
}
} else {
Utils.closeKeyboard(getActivity(), this.mEmailEditText);
LoginEvent event = new LoginEvent(R.id.button_login, email, password);
BusProvider.getInstance().post(event);
}
}
Then the login event:
private void login(final ButtonEvent buttonEvent) {
LoginEvent loginEvent = (LoginEvent) buttonEvent;
new LoginTask().execute();
email = loginEvent.getEmail();
password = loginEvent.getPassword();
}
And finally the login process with Firebase in a AsyncTask.
private class LoginTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(StartActivity.this);
progressDialog.setTitle(“please wait..");
progressDialog.setMessage(“authorizing...");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
mFirebase.authWithPassword(email, password, new Firebase.AuthResultHandler() {
#Override
public void onAuthenticated(AuthData authData) {
// System.out.println("User ID: " + authData.getUid() + ", Provider: " + authData.getProvider());
Intent intent2 = new Intent(StartActivity.this, MainActivity.class);
startActivity(intent2);
finish();
}
#Override
public void onAuthenticationError(FirebaseError firebaseError) {
// error encountered
switch (firebaseError.getCode()) {
case FirebaseError.USER_DOES_NOT_EXIST:
// handle a non existing user
Toast.makeText(getApplicationContext(), getString(R.string.error_user_not_exist)
Toast.LENGTH_LONG).show();
break;
case FirebaseError.INVALID_PASSWORD:
// handle an invalid password
Toast.makeText(getApplicationContext(), getString(R.string.error_invalid_password)
Toast.LENGTH_LONG).show();
break;
default:
// handle other errors
Toast.makeText(getApplicationContext(), getString(R.string.error_reset_password),
Toast.LENGTH_LONG).show();
break;
}
}
});
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
progressDialog.dismiss();
}
}

Facebook login button causes a crash

I have trouble trying to solve Facebook login button as a part of Android application.
Application starts well, but it crashes when I press Facebook Login button.
This is what it says in log:
12-06 17:17:01.079 25678-25678/com.example.icen.tij01 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.icen.tij01, PID: 25678
java.lang.NullPointerException: Attempt to invoke virtual method 'android.support.v4.app.Fragment com.facebook.internal.FragmentWrapper.getSupportFragment()' on a null object reference
at com.facebook.FacebookButtonBase.getFragment(FacebookButtonBase.java:105)
at com.facebook.login.widget.LoginButton$LoginClickListener.onClick(LoginButton.java:736)
at com.facebook.FacebookButtonBase$1.onClick(FacebookButtonBase.java:383)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
12-06 17:17:03.055 25678-25678/com.example.icen.tij01 I/Process: Sending signal. PID: 25678 SIG: 9
UPDATE:
And this is part of Activity that have to handle Facebook login:
package com.example.icen.tij01;
import android.app.Activity;
/* import... */
public class StartActivity extends ActionBarActivity {
static String hostDomain = "http://192.168.48.1/myPhpApp/";
private TextView info;
private LoginButton loginButton;
private CallbackManager callbackManager;
static String checkUrl = hostDomain + "connect.php";
String responseServer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
setContentView(R.layout.activity_start);
info = (TextView)findViewById(R.id.info);
loginButton = (LoginButton)findViewById(R.id.login_button);
// redirekicija na formu za logovanje
Button btnLogin = (Button) findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent loginForm = new Intent(StartActivity.this, LoginFormActivity.class);
startActivity(loginForm);
}
});
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
info.setText(
"User ID: "
+ loginResult.getAccessToken().getUserId()
+ "\n" +
"Auth Token: "
+ loginResult.getAccessToken().getToken()
);
}
#Override
public void onCancel() {
info.setText("Login attempt canceled.");
}
#Override
public void onError(FacebookException e) {
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
}
#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_start, 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);
}
/* Inner class to get response */
class AsyncT extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(checkUrl);
try {
JSONObject jsonobj = new JSONObject();
jsonobj.put("name", "Aneh");
jsonobj.put("age", "22");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("req", jsonobj.toString()));
Log.e("mainToPost", "mainToPost" + nameValuePairs.toString());
// Use UrlEncodedFormEntity to send in proper format which we need
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
InputStream inputStream = response.getEntity().getContent();
InputStreamToStringExample str = new InputStreamToStringExample();
responseServer = str.getStringFromInputStream(inputStream);
//Log.e("response", "response -----" + responseServer);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast;
if(responseServer.trim().equals("1")) {
toast = Toast.makeText(context, "Connection ok, redirecting to adverts...", duration);
toast.show();
Intent show = new Intent(StartActivity.this, MainActivity.class);
startActivity(show);
} else {
toast = Toast.makeText(context, "Connection error", duration);
toast.show();
AlertDialog alertDialog = new AlertDialog.Builder(StartActivity.this).create();
alertDialog.setTitle("Connection error");
alertDialog.setMessage("Error. Please check your connection");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
}
}
public static class InputStreamToStringExample {
public static void main(String[] args) throws IOException {
// intilize an InputStream
InputStream is =
new ByteArrayInputStream("file content..blah blah".getBytes());
String result = getStringFromInputStream(is);
System.out.println(result);
System.out.println("Done");
}
// convert InputStream to String
private static String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
}
}
I followed several tutorials, like:
http://code.tutsplus.com/tutorials/quick-tip-add-facebook-login-to-your-android-app--cms-23837
Can you help me how to solve this, please.
The problem is with facebook login button. For some reason it is not initialized.
I tried a lot of different ways to resolve this issue. And ended up with two solutions.
1) Change your class to extend fragment.And setFragment to your fb_login_button as per
https://developers.facebook.com/docs/facebook-login/android
{
loginButton = (LoginButton) view.findViewById(R.id.login_button);
loginButton.setReadPermissions("user_friends");
loginButton.setFragment(this);
}
2) Instead of facebook_login_button create a custom button.
And on the onClickListener call a method which has callBackManager and LoginManager.
{
Custom button in login_activity
<Button
android:id="#+id/fb_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background = "#drawable/btn_facebook"
/>
Login_Activity
fb_btn = (Button) findViewById(R.id.fb_btn);
fb_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onfbClick();
}
});
Method to call LoginManager
private void onfbClick() {
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("email","public_profile"));
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
Bundle parameters = new Bundle();
parameters.putString("fields", "first_name,last_name");
//request.setParameters(parameters);
//request.executeAsync();
}
#Override
public void onCancel() {
Log.i(TAG, "onCancel triggered");
}
#Override
public void onError(FacebookException exception) {
Log.i(TAG, "onError triggered");
}
});
}
}
It's hard to see where or why you have a Null Pointer Exception when the Fragment is being invoked, also because it's a custom example.
I suggest that you give Simple Facebook a try, it will make your life with Facebook a lot easier.

android message is not posting on twitter

I am trying to post my message on twitter. When I click on button, it shows me message that your data has been posted on twitter,but when I check I don't get any message. Here is my code.
btnUpdateStatus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Call update status function
// Get the status from EditText
String status = txtUpdate.getText().toString();
new updateTwitterStatus().execute(status);
}
});
here is update twitterstatus class
private class updateTwitterStatus extends AsyncTask<String,Void,Void>
{
#Override
protected void onPreExecute()
{
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Updating to twitter...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(String... screen_name)
{
String status = null;
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
// Access Token
String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
// Access Token Secret
String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");
AccessToken accessToken = new AccessToken(access_token, access_token_secret);
Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
// Update status
twitter4j.Status response = twitter.updateStatus(status);
Log.i(""+response, "value");
Log.d("Status", "> " + response.getText());
} catch (TwitterException e) {
// Error in updating status
Log.d("Twitter Update Error", e.getMessage());
e.printStackTrace();
}
return null;
}
/// }
#Override
protected void onPostExecute(Void result)
{
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Status tweeted successfully", Toast.LENGTH_SHORT)
.show();
// Clearing EditText field
txtUpdate.setText("");
}
});
}
}
please help me. I am finding for this since a couple of days, I know I have asked this but I am not getting any appropriate solution, thankyou.
For twitter there are two libraries.
Twitter4j.jar (For text wall post)
Twitpick.jar (for picture post)
Either you can go for SocialAuth library (Well managed and simple to use)

Android asynctask not displaying anything

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!

Categories

Resources