Cannot convert java.lang.string into json object - android

This project is about login where i am trying to login and getting this error.Cannot convert json obj to java.lang . String
what should i do to resolve this error?
i am getting an error in json object even when i was passing a string value now i change the string value to exact same value where i was getting an error .
I have tried many things to resolve it by making a string object and then passing it instead of response
But it then showed an error cannot expect a literal value ay character 1.
This is the PATH of the DB_FUNCTIONS.PHP that it is a string value.
/home/awesogp3/public_html/android_login_api/include/DB_Functions.php"
here is my DB_FUNCTIONS.PHP
<?php
class DB_Functions {
private $conn;
// constructor
function __construct() {
require_once 'DB_Connect.php';
// connecting to database
$db = new Db_Connect();
$this->conn = $db->connect();
}
// destructor
function __destruct() {
}
/**
* Storing new user
* returns user details
*/
public function storeUser($name, $email, $password) {
$uuid = uniqid('', true);
$hash = $this->hashSSHA($password);
$encrypted_password = $hash["encrypted"]; // encrypted password
$salt = $hash["salt"]; // salt
$stmt = $this->conn->prepare("INSERT INTO users(unique_id, name, email, encrypted_password, salt, created_at) VALUES(?, ?, ?, ?, ?, NOW())");
$stmt->bind_param("sssss", $uuid, $name, $email, $encrypted_password, $salt);
$result = $stmt->execute();
$stmt->close();
// check for successful store
if ($result) {
$stmt = $this->conn->prepare("SELECT * FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();
return $user;
} else {
return false;
}
}
/**
* Get user by email and password
*/
public function getUserByEmailAndPassword($email, $password) {
$stmt = $this->conn->prepare("SELECT * FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
if ($stmt->execute()) {
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();
// verifying user password
$salt = $user['salt'];
$encrypted_password = $user['encrypted_password'];
$hash = $this->checkhashSSHA($salt, $password);
// check for password equality
if ($encrypted_password == $hash) {
// user authentication details are correct
return $user;
}
} else {
return NULL;
}
}
/**
* Check user is existed or not
*/
public function isUserExisted($email) {
$stmt = $this->conn->prepare("SELECT email from users WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
// user existed
$stmt->close();
return true;
} else {
// user not existed
$stmt->close();
return false;
}
}
/**
* Encrypting password
* #param password
* returns salt and encrypted password
*/
public function hashSSHA($password) {
$salt = sha1(rand());
$salt = substr($salt, 0, 10);
$encrypted = base64_encode(sha1($password . $salt, true) . $salt);
$hash = array("salt" => $salt, "encrypted" => $encrypted);
return $hash;
}
/**
* Decrypting password
* #param salt, password
* returns hash string
*/
public function checkhashSSHA($salt, $password) {
$hash = base64_encode(sha1($password . $salt, true) . $salt);
return $hash;
}
}
?>
Here is my LoginActivity.java where i am trying to login and getting this error.
package com.example.dhruv.bill;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.dhruv.bill.R;
import com.example.dhruv.bill.AppConfig;
import com.example.dhruv.bill.AppController;
import com.example.dhruv.bill.SQLiteHandler;
import com.example.dhruv.bill.SessionManager;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class LoginActivity extends Activity {
private static final String TAG = RegisterActivity.class.getSimpleName();
private Button btnLogin;
private Button btnLinkToRegister;
private EditText inputEmail;
private EditText inputPassword;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;
public static final String ID_INTENTEXT = SQLiteHandler.KEY_NAME + "_INTENTEXTRA";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
allow_volley av = new allow_volley();
av.allow();
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// SQLite database handler
db = new SQLiteHandler(getApplicationContext());
// Session manager
session = new SessionManager(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString().trim();
String password = inputPassword.getText().toString().trim();
Log.d(TAG, "Login Response: " + email);
Log.d(TAG, "Login Response: " + password);
// Check for empty data in the form
if (!email.isEmpty() && !password.isEmpty()) {
// login user
checkLogin(email, password);
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(),
"Please enter the credentials!", Toast.LENGTH_LONG)
.show();
}
}
});
// Link to Register Screen
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
finish();
}
});
}
/**
* function to verify login details in mysql db
* */
private void checkLogin(final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_login";
pDialog.setMessage("Logging in ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
// user successfully logged in
// Create login session
session.setLogin(true);
// Now store the user in SQLite
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
String name = user.getString("name");
String email = user.getString("email");
String created_at = user
.getString("created_at");
// Inserting row in users table
db.addUser(name, email, uid, created_at);
// Launch main activity
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
finish();
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
Log.d(TAG, "Login Response: " + email);
Log.d(TAG, "Login Response: " + password);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
This is the log cat
Notice: Use of undefined constant home - assumed 'home' in /home/awesogp3/public_html/android_login_api/include/DB_Functions.php on line 2
Notice: Use of undefined constant public_html - assumed 'public_html' in /home/awesogp3/public_html/android_login_api/include/DB_Functions.php on line 2
Warning: Division by zero in /home/awesogp3/public_html/android_login_api/include/DB_Functions.php on line 2
Notice: Use of undefined constant awesogp3 - assumed 'awesogp3' in /home/awesogp3/public_html/android_login_api/include/DB_Functions.php on line 2
Warning: Division by zero in /home/awesogp3/public_html/android_login_api/include/DB_Functions.php on line 2
Notice: Use of undefined constant android_login_api - assumed 'android_login_api' in /home/awesogp3/public_html/android_login_api/include/DB_Functions.php on line 2
Warning: Division by zero in /home/awesogp3/public_html/android_login_api/include/DB_Functions.php on line 2
false
Fatal error: Call to undefined method mysqli_stmt::get_result() in /home/awesogp3/public_html/android_login_api/include/DB_Functions.php on line 60

Related

app crashes when try to create new record on remote database mysql using volley

I have created a simple android app which connect to Remote sql database.. the problem is when I click on register the application crash. please help me guys
package com.example.akshay.webservices;
/**
* Created by Akshay on 7/20/2015.
*/
import com.example.akshay.webservices.AppConfig;
import com.example.akshay.webservices.AppController;
import com.example.akshay.webservices.SQLiteHandler;
import com.example.akshay.webservices.SessionManager;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
public class RegisterActivity extends Activity {
private static final String TAG = RegisterActivity.class.getSimpleName();
private Button btnRegister;
private Button btnLinkToLogin;
private EditText inputFullName;
private EditText inputEmail;
private EditText inputPassword;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
inputFullName = (EditText) findViewById(R.id.name);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// Session manager
session = new SessionManager(getApplicationContext());
// SQLite database handler
db = new SQLiteHandler(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(RegisterActivity.this,
MainActivity.class);
startActivity(intent);
finish();
}
// Register Button Click event
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String name = inputFullName.getText().toString();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
if (!name.isEmpty() && !email.isEmpty() && !password.isEmpty()) {
registerUser(name, email, password);
} else {
Toast.makeText(getApplicationContext(),
"Please enter your details!", Toast.LENGTH_LONG)
.show();
}
}
});
// Link to Login Screen
btnLinkToLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
LoginActivity.class);
startActivity(i);
finish();
}
});
}
/**
* Function to store user in MySQL database will post params(tag, name,
* email, password) to register url
* */
private void registerUser(final String name, final String email,
final String password) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Registering ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
// User successfully stored in MySQL
// Now store the user in sqlite
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
String name = user.getString("name");
String email = user.getString("email");
String created_at = user
.getString("created_at");
// Inserting row in users table
db.addUser(name, email, uid, created_at);
// Launch login activity
Intent intent = new Intent(
RegisterActivity.this,
LoginActivity.class);
startActivity(intent);
finish();
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "register");
params.put("name", name);
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
AppController.java
package com.example.akshay.webservices;
import android.app.Application;
/**
* Created by Akshay on 7/19/2015.
*/
import android.app.Application;
import android.text.TextUtils;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
LogCat:
07-20 20:27:07.195 8233-8233/? E/Zygote﹕ MountEmulatedStorage()
07-20 20:27:07.195 8233-8233/? E/Zygote﹕ v2
07-20 20:27:07.195 8233-8233/? E/SELinux﹕ [DEBUG] get_category: variable seinfo: default sensitivity: NULL, cateogry: NULL
07-20 20:27:18.355 8233-8233/com.example.akshay.webservices E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.akshay.webservices, PID: 8233
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.akshay.webservices.AppController.addToRequestQueue(com.android.volley.Request, java.lang.String)' on a null object reference
at com.example.akshay.webservices.RegisterActivity.registerUser(RegisterActivity.java:185)
at com.example.akshay.webservices.RegisterActivity.access$300(RegisterActivity.java:32)
at com.example.akshay.webservices.RegisterActivity$1.onClick(RegisterActivity.java:81)
at android.view.View.performClick(View.java:5191)
at android.view.View$PerformClick.run(View.java:20916)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5972)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
This is the logcat I am unable to understand what is happening. Please help..
Problem is happening cause AppController.getInstance() it's returning null,
you have to change your AppController.getInstance() method to be this way:
public static AppController getInstance() {
if (mInstance == null) {
mInstance = new AppController;
}
return mInstance;
}
also make sure that you are registering your app class in your manifest
you should have an attribute in your manifest app like this:
<application
android:name="package.AppController" <--------
android:allowBackup="true"
android:debuggable="true"
android:icon="#drawable/ic_launcher"
android:label="xyz"
android:screenOrientation="landscape"
android:theme="#style/AppTheme">
More info here: http://developer.android.com/reference/android/app/Application.html
"Base class for those who need to maintain global application state. You can provide your own implementation by specifying its name in your AndroidManifest.xml's tag, which will cause that class to be instantiated for you when the process for your application/package is created. "
Hey i had the same issue and when i tried this solution it did not work finally i got a way out.
The problem why it is returning a null pointer is because the methods getInstance() and getRequestQueue() are returning nothing with respect to the context. To solve that follow this steps. As prerequisite ad the following global variable in under public class AppController extends Application private Context myContext.
STEP 1.
Create a constructor that defines the context
public AppController(Context context){
myContext = context;
mRequestQueue = getRequestQueue();
}
STEP 2. Modify hyou getInstance() method to work within the context as follow:
public static synchronized AppController getInstance(Context context) {
if(mInstance==null){
mInstance = new AppController(context);
}
return mInstance;
}
Step 3.
Finally modify the getRequestQueue() method to work within the context as follows
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(myContext.getApplicationContext());
}
return mRequestQueue;
}
Finally got the calling class and call the methods from AppController.java with respect to the context of the activity or broadcaster.
AppController.getInstance(this).addToRequestQueue(strReq, tag_string_req);

Null Object Reference Error: Android Studio using SQLite

So I'm trying to adapt this tutorial: http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/
to my own project. It is a basic register & login in Android/Java using SQLite & Volley to a SQL server via PHP.
I can get the tutorial as written working no problem. However, upon transferring it to my project I encounter a crash;
05-12 01:18:05.763 1965-1965/com.disclosure_scots.disclosure_scots E/AndroidRuntime? FATAL EXCEPTION: main
Process: com.disclosure_scots.disclosure_scots, PID: 1965
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.disclosure_scots.disclosure_scots.AppController.addToRequestQueue(com.android.volley.Request, java.lang.String)' on a null object reference
at com.disclosure_scots.disclosure_scots.RegisterActivity.registerUser(RegisterActivity.java:194)
at com.disclosure_scots.disclosure_scots.RegisterActivity.access$300(RegisterActivity.java:34)
at com.disclosure_scots.disclosure_scots.RegisterActivity$1.onClick(RegisterActivity.java:90)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
The line within RegisterActivity to which it refers too is;
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
The Activities involved are;
RegisterActivity
package com.disclosure_scots.disclosure_scots;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.disclosure_scots.disclosure_scots.AppConfig;
import com.disclosure_scots.disclosure_scots.AppController;
import com.disclosure_scots.disclosure_scots.SQLiteHandler;
import com.disclosure_scots.disclosure_scots.SessionManager;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
public class RegisterActivity extends ActionBarActivity {
private static final String TAG = RegisterActivity.class.getSimpleName();
private Button btnRegister;
private EditText inputFullName;
private EditText inputEmail;
private EditText inputPassword;
private EditText inputTel_No;
private EditText inputHome_Add;
private EditText inputPostcode;
private CheckBox inputPostal;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
inputFullName = (EditText) findViewById(R.id.editTextName);
inputEmail = (EditText) findViewById(R.id.editTextEmail);
inputPassword = (EditText) findViewById(R.id.editTextPass);
inputTel_No = (EditText) findViewById(R.id.editTextPhone);
inputHome_Add = (EditText) findViewById(R.id.editTextPost);
inputPostcode = (EditText) findViewById(R.id.editTextPostcode);
inputPostal = (CheckBox) findViewById(R.id.PostalcheckBox);
btnRegister = (Button) findViewById(R.id.btnRegister);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// Session manager
session = new SessionManager(getApplicationContext());
// SQLite database handler
db = new SQLiteHandler(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn()) {
// User is already logged in. Take him to Legal disclaimer activity
Intent intent = new Intent(RegisterActivity.this,
LegalDiscActivity.class);
startActivity(intent);
finish();
}
// Register Button Click event
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String name = inputFullName.getText().toString();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
if (!name.isEmpty() && !email.isEmpty() && !password.isEmpty()) {
registerUser(name, email, password);
} else {
Toast.makeText(getApplicationContext(),
"Please enter your details!", Toast.LENGTH_LONG)
.show();
}
}
});
// Link to Login Screen
/*btnLinkToLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
LoginActivity.class);
startActivity(i);
finish();
}
});*/
}
/**
* Function to store user in MySQL database will post params(tag, name,
* email, password) to register url
* */
private void registerUser(final String name, final String email,
final String password) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Registering ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
// User successfully stored in MySQL
// Now store the user in sqlite
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
String name = user.getString("name");
String email = user.getString("email");
String created_at = user
.getString("created_at");
// Inserting row in users table
db.addUser(name, email, uid, created_at);
// Launch login activity
Intent intent = new Intent(
RegisterActivity.this,
LoginActivity.class);
startActivity(intent);
finish();
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "register");
params.put("name", name);
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
#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_register, 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);
}
}
AppController class
package com.disclosure_scots.disclosure_scots;
/**
* Created by Administrator on 09/05/2015.
*/
import android.app.Application;
import android.text.TextUtils;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
I've been over it a number of times but cannot tell why I am getting the null object in my copied version while the original works fine.
Any help appreciated.
This is very likely because you didn't register your AppController in the manifest so getInstance returns null.
you need to add this line in your manifest (may be you missed this line so it returns null value)
<application
android:name="(your app package).app.AppController" // <--this line
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
...../>

android twitter integration using AsyncTask

plz help me in integrating twitter in my android app account using AsyncTask . I m following androidhive tutorial on integrating twitter account but i am getting Network on main thread exception.
Thanks in advance :D
This is the link of code
http://www.androidhive.info/2012/09/android-twitter-oauth-connect-tutorial/
and this is my MainActivity.java
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
// Constants
/**
* Register your here app https://dev.twitter.com/apps/new and get your
* consumer key and secret
* */
static String TWITTER_CONSUMER_KEY = ""; // place your cosumer key here
static String TWITTER_CONSUMER_SECRET = ""; // place your consumer secret here
// Preference Constants
static String PREFERENCE_NAME = "twitter_oauth";
static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
static final String TWITTER_CALLBACK_URL = "oauth://t4jsample";
// Twitter oauth urls
static final String URL_TWITTER_AUTH = "auth_url";
static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";
// Login button
Button btnLoginTwitter;
// Update status button
Button btnUpdateStatus;
// Logout button
Button btnLogoutTwitter;
// EditText for update
EditText txtUpdate;
// lbl update
TextView lblUpdate;
TextView lblUserName;
// Progress dialog
ProgressDialog pDialog;
// Twitter
private static Twitter twitter;
private static RequestToken requestToken;
// Shared Preferences
private static SharedPreferences mSharedPreferences;
// Internet Connection detector
private ConnectionDetector cd;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(MainActivity.this, "Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// Check if twitter keys are set
if(TWITTER_CONSUMER_KEY.trim().length() == 0 || TWITTER_CONSUMER_SECRET.trim().length() == 0){
// Internet Connection is not present
alert.showAlertDialog(MainActivity.this, "Twitter oAuth tokens", "Please set your twitter oauth tokens first!", false);
// stop executing code by return
return;
}
// All UI elements
btnLoginTwitter = (Button) findViewById(R.id.btnLoginTwitter);
btnUpdateStatus = (Button) findViewById(R.id.btnUpdateStatus);
btnLogoutTwitter = (Button) findViewById(R.id.btnLogoutTwitter);
txtUpdate = (EditText) findViewById(R.id.txtUpdateStatus);
lblUpdate = (TextView) findViewById(R.id.lblUpdate);
lblUserName = (TextView) findViewById(R.id.lblUserName);
// Shared Preferences
mSharedPreferences = getApplicationContext().getSharedPreferences(
"MyPref", 0);
/**
* Twitter login button click event will call loginToTwitter() function
* */
btnLoginTwitter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Call login twitter function
loginToTwitter();
}
});
/**
* Button click event to Update Status, will call updateTwitterStatus()
* function
* */
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();
// Check for blank text
if (status.trim().length() > 0) {
// update status
new updateTwitterStatus().execute(status);
} else {
// EditText is empty
Toast.makeText(getApplicationContext(),
"Please enter status message", Toast.LENGTH_SHORT)
.show();
}
}
});
/**
* Button click event for logout from twitter
* */
btnLogoutTwitter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Call logout twitter function
logoutFromTwitter();
}
});
/** This if conditions is tested once is
* redirected from twitter page. Parse the uri to get oAuth
* Verifier
* */
if (!isTwitterLoggedInAlready()) {
Uri uri = getIntent().getData();
if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
// oAuth verifier
String verifier = uri
.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
try {
// Get the access token
AccessToken accessToken = twitter.getOAuthAccessToken(
requestToken, verifier);
// Shared Preferences
Editor e = mSharedPreferences.edit();
// After getting access token, access token secret
// store them in application preferences
e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
e.putString(PREF_KEY_OAUTH_SECRET,
accessToken.getTokenSecret());
// Store login status - true
e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
e.commit(); // save changes
Log.e("Twitter OAuth Token", "> " + accessToken.getToken());
// Hide login button
btnLoginTwitter.setVisibility(View.GONE);
// Show Update Twitter
lblUpdate.setVisibility(View.VISIBLE);
txtUpdate.setVisibility(View.VISIBLE);
btnUpdateStatus.setVisibility(View.VISIBLE);
btnLogoutTwitter.setVisibility(View.VISIBLE);
// Getting user details from twitter
// For now i am getting his name only
long userID = accessToken.getUserId();
User user = twitter.showUser(userID);
String username = user.getName();
// Displaying in xml ui
lblUserName.setText(Html.fromHtml("<b>Welcome " + username + "</b>"));
} catch (Exception e) {
// Check log for login errors
Log.e("Twitter Login Error", "> " + e.getMessage());
}
}
}
}
/**
* Function to login twitter
* */
private void loginToTwitter() {
// Check if already logged in
if (!isTwitterLoggedInAlready()) {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
Configuration configuration = builder.build();
TwitterFactory factory = new TwitterFactory(configuration);
twitter = factory.getInstance();
try {
requestToken = twitter
.getOAuthRequestToken(TWITTER_CALLBACK_URL);
this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
.parse(requestToken.getAuthenticationURL())));
} catch (TwitterException e) {
e.printStackTrace();
}
} else {
// user already logged into twitter
Toast.makeText(getApplicationContext(),
"Already Logged into twitter", Toast.LENGTH_LONG).show();
}
}
/**
* Function to update status
* */
class updateTwitterStatus extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Updating to twitter...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Places JSON
* */
protected String doInBackground(String... args) {
Log.d("Tweet Text", "> " + args[0]);
String status = args[0];
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.d("Status", "> " + response.getText());
} catch (TwitterException e) {
// Error in updating status
Log.d("Twitter Update Error", e.getMessage());
}
return null;
}
/**
* After completing background task Dismiss the progress dialog and show
* the data in UI Always use runOnUiThread(new Runnable()) to update UI
* from background thread, otherwise you will get error
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
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("");
}
});
}
}
/**
* Function to logout from twitter
* It will just clear the application shared preferences
* */
private void logoutFromTwitter() {
// Clear the shared preferences
Editor e = mSharedPreferences.edit();
e.remove(PREF_KEY_OAUTH_TOKEN);
e.remove(PREF_KEY_OAUTH_SECRET);
e.remove(PREF_KEY_TWITTER_LOGIN);
e.commit();
// After this take the appropriate action
// I am showing the hiding/showing buttons again
// You might not needed this code
btnLogoutTwitter.setVisibility(View.GONE);
btnUpdateStatus.setVisibility(View.GONE);
txtUpdate.setVisibility(View.GONE);
lblUpdate.setVisibility(View.GONE);
lblUserName.setText("");
lblUserName.setVisibility(View.GONE);
btnLoginTwitter.setVisibility(View.VISIBLE);
}
/**
* Check user already logged in your application using twitter Login flag is
* fetched from Shared Preferences
* */
private boolean isTwitterLoggedInAlready() {
// return twitter login status from Shared Preferences
return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
}
protected void onResume() {
super.onResume();
}
}
You might got this error most probably in 4.0 device or IF the http conncetion is taking too long to respond.
if you dont know asynctask then simple solution will be
public static boolean isAuthenticated(Context context) {
new Thread() {
#Override
public void run() {
TwitterPrefrences twitterPref = new TwitterPrefrences(context);
String token = twitterPref.getTwitterAuthToken();
String secret = twitterPref.getTwitterAuthTokenSecrate();
AccessToken a = new AccessToken(token,secret);
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(Constants.TWITT_CONSUMER_KEY,Constants.TWITT_CONSUMER_SECRET);
twitter.setOAuthAccessToken(a);
try {
twitter.getAccountSettings();
return true;
} catch (TwitterException e) {
return false;
}
}
}.start();
}

Quick Unresolved Class Issue

I get an error on line 80 (userFunction.logoutUser(getApplicationContext());) That says userFunction cannot be resolved. I have defined userFunction and have already tried to use the full package name and things, so what can I do to get rid of this error really quick? (Asked this question mostly for future reference since this happens a lot) Thanks!
package com.example.dashboardactivity;
import libary.UserFunctions;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class LoginActivity extends Activity {
public final String TAG = "LoginActivity";
Button btnLogin;
Button btnLinkToRegister;
EditText inputEmail;
EditText inputPassword;
TextView loginErrorMsg;
// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
// Importing all assets like buttons, text fields
inputEmail = (EditText) findViewById(R.id.loginEmail);
inputPassword = (EditText) findViewById(R.id.loginPassword);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
loginErrorMsg = (TextView) findViewById(R.id.login_error);
// Login button Click Event
Log.i(TAG, "LoginActivity Login button Click Event" );
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
new AsyncTask<String, Void, JSONObject>(){
#Override
protected JSONObject doInBackground(String... args) { //This is run on a background thread
String email = args[0];
String password = args[1];
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.loginUser(email, password);
return json;
}
#Override
protected void onPostExecute(JSONObject json) { //This is run on the UI thread
if(json != null){
//... update the user interface ...
Log.i(TAG, "checking for login response");
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
loginErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully logged in
// Store user details in SQLite Database
libary.DatabaseHandler db = new libary.DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
// Clear all previous data in database
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
// Launch Dashboard Screen
Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Registration Screen
finish();
}else{
// Error in login
loginErrorMsg.setText("Incorrect username/password");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
else{
Log.e("LoginTask", "No login response was received");
}
super.onPostExecute(json);
}
}.execute(inputEmail.getText().toString(), inputPassword.getText().toString());
}
});
// Link to Register Screen
Log.i(TAG, "LoginActivity btnLinkToRegister" );
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
finish();
}
});
}
}
You've defined UserFunctions userFunction = new UserFunctions(); inside the doInBackground method but are trying to access the variable in onPostExecute.
Try to declare UserFunctions userFunction; outside the doInBackground so that it is accessible to other functions.
new AsyncTask<String, Void, JSONObject>(){
UserFunctions userFunction;
#Override
protected JSONObject doInBackground(String... args) { //This is run on a background thread
userFunction = new UserFunctions();
}
#Override
protected void onPostExecute(JSONObject json) {
userFunction.logoutUser(getApplicationContext());
}
}

how to get home timeline data from twitter

I have developed one application.In my application i want to get twitter home timeline data and displaying listview.And i have used twitter4j library.I have searched a lot and also read twitter documentation.In taht documentation getting user timeline data by using the bellow webservice: "https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=twitterapi&count=2".It is working fine and data will be displayed.But my requirement is getting home timeline data.In that documentation they given following webservice: https://api.twitter.com/1.1/statuses/home_timeline.json.This is not working and home timeline data wont be displayed.please any one suggest me,how to do this.Thanks in advance
This is my oncreate code:This is my impotrs:
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import com.dss.utils.UrltoValue;
import com.ibud.adapters.TweetList;
import twitter4j.Paging;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import twitter4j.json.DataObjectFactory;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.preference.PreferenceManager;
import android.text.Html;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
And this is my instance variables:
static String TWITTER_CONSUMER_KEY = "CjHtStxCA2toDQY6xnMwg"; // place your cosumer key here
static String TWITTER_CONSUMER_SECRET = "jjhpODDhtl3FM26ETn7yt3Q1Wc7VdxZXequDrmwFg"; // place your consumer secret here
// Preference Constants
static String PREFERENCE_NAME = "twitter_oauth";
static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
static final String TWITTER_CALLBACK_URL = "oauth://t4jsample";
// Twitter oauth urls
static final String URL_TWITTER_AUTH = "auth_url";
static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";
String username="";
private String strResponse;
private String[] strText;
LinearLayout llTotal;
ListView lvlist;
List<Status> statuses = new ArrayList<Status>();
// Login button
Button btnLoginTwitter,btnLoginFaceBook,btnBack;
// Update status button
Button btnUpdateStatus;
// Logout button
Button btnLogoutTwitter;
// EditText for update
EditText txtUpdate;
// lbl update
TextView lblUpdate;
TextView lblUserName;
// Progress dialog
ProgressDialog pDialog;
// Twitter
private static Twitter twitter;
private static RequestToken requestToken;
// Shared Preferences
private static SharedPreferences mSharedPreferences;
// Internet Connection detector
private ConnectionDetector cd;
AccessToken accessToken;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(MainActivity.this,
"Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// Check if twitter keys are set
if (TWITTER_CONSUMER_KEY.trim().length() == 0
|| TWITTER_CONSUMER_SECRET.trim().length() == 0) {
// Internet Connection is not present
alert.showAlertDialog(MainActivity.this, "Twitter oAuth tokens",
"Please set your twitter oauth tokens first!", false);
// stop executing code by return
return;
}
// All UI elements
btnBack = (Button) findViewById(R.id.back);
btnLoginFaceBook = (Button) findViewById(R.id.btnLoginFaceBook);
btnLoginTwitter = (Button) findViewById(R.id.btnLoginTwitter);
btnUpdateStatus = (Button) findViewById(R.id.btnUpdateStatus);
btnLogoutTwitter = (Button) findViewById(R.id.btnLogoutTwitter);
txtUpdate = (EditText) findViewById(R.id.txtUpdateStatus);
lblUpdate = (TextView) findViewById(R.id.lblUpdate);
lblUserName = (TextView) findViewById(R.id.lblUserName);
// Shared Preferences
mSharedPreferences = getApplicationContext().getSharedPreferences(
"MyPref", 0);
btnLoginTwitter.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
loginToTwitter();
}
});
btnBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Call login twitter function
btnLogoutTwitter.setVisibility(View.GONE);
btnUpdateStatus.setVisibility(View.GONE);
txtUpdate.setVisibility(View.GONE);
lblUpdate.setVisibility(View.GONE);
lblUserName.setText("");
lblUserName.setVisibility(View.GONE);
btnLoginFaceBook.setVisibility(View.VISIBLE);
btnLoginTwitter.setVisibility(View.VISIBLE);
}
});
btnLoginFaceBook.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Call login twitter function
Log.e("this is", "facebook onclick");
}
});
/**
* Button click event to Update Status, will call updateTwitterStatus()
* function
* */
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();
// Check for blank text
if (status.trim().length() > 0) {
// update status
new updateTwitterStatus().execute(status);
} else {
// EditText is empty
Toast.makeText(getApplicationContext(),
"Please enter status message",
Toast.LENGTH_SHORT).show();
}
}
});
/**
* Button click event for logout from twitter
* */
btnLogoutTwitter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Call logout twitter function
logoutFromTwitter();
}
});
/**
* This if conditions is tested once is redirected from twitter page.
* Parse the uri to get oAuth Verifier
* */
if (!isTwitterLoggedInAlready()) {
Uri uri = getIntent().getData();
if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
// oAuth verifier
String verifier = uri
.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
try {
// Get the access token
accessToken = twitter.getOAuthAccessToken(requestToken,
verifier);
// Shared Preferences
Editor e = mSharedPreferences.edit();
// After getting access token, access token secret
// store them in application preferences
e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
e.putString(PREF_KEY_OAUTH_SECRET,
accessToken.getTokenSecret());
// Store login status - true
e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
e.commit(); // save changes
Log.e("Twitter OAuth Token", "> " + accessToken.getToken());
// Hide login button
btnLoginTwitter.setVisibility(View.GONE);
btnLoginFaceBook.setVisibility(View.GONE);
// Show Update Twitter
lblUpdate.setVisibility(View.VISIBLE);
txtUpdate.setVisibility(View.VISIBLE);
btnUpdateStatus.setVisibility(View.VISIBLE);
btnLogoutTwitter.setVisibility(View.VISIBLE);
// Getting user details from twitter
// For now i am getting his name only
long userID = accessToken.getUserId();
User user = twitter.showUser(userID);
String username = user.getName();
Log.e("user id:", "" + userID);
Log.e("user name:", username);
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
Log.e("tryyyyyyyyy:", "try");
// TWITTER ACCESS TOKEN
String twit_access_token = mSharedPreferences
.getString(PREF_KEY_OAUTH_TOKEN, null);
Log.e("access token:", twit_access_token);
// TWITTER ACCESS TOKEN SECRET
String twit_access_token_secret = mSharedPreferences
.getString(PREF_KEY_OAUTH_SECRET, null);
Log.e("access token sec:", twit_access_token_secret);
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
builder.setOAuthAccessToken(twit_access_token);
builder.setOAuthAccessTokenSecret(twit_access_token_secret);
builder.setJSONStoreEnabled(true);
builder.setIncludeEntitiesEnabled(true);
// builder.setIncludeMyRetweetEnabled(true);
builder.setIncludeRTsEnabled(true);
AccessToken accessToken = new AccessToken(
twit_access_token, twit_access_token_secret);
Log.e("accesstoken:", "" + accessToken);
Twitter twitter = new TwitterFactory(builder.build())
.getInstance(accessToken);
Log.e("twitter:", "" + twitter);
Paging paging = new Paging(200); // MAX 200 IN ONE CALL.
// SET YOUR OWN
// NUMBER <= 200
statuses = twitter.getHomeTimeline(paging);
Log.e("statuses", "statuses");
try {
Log.e("tryyyyyyyyy in tryyyyyyyyyyyyyy:", "try");
String strInitialDataSet = DataObjectFactory
.getRawJSON(statuses);
JSONArray JATweets = new JSONArray(
strInitialDataSet);
Log.e("lengthhhhhhhhhhhh:", "" + JATweets.length());
for (int i = 0; i < JATweets.length(); i++) {
JSONObject JOTweets = JATweets.getJSONObject(i);
Log.e("TWEETS", JOTweets.toString());
}
} catch (Exception e1) {
// TODO: handle exception
e1.printStackTrace();
}
} catch (Exception e2) {
// TODO: handle exception
}
// Displaying in xml ui
lblUserName.setText(Html.fromHtml("<b>Welcome " + username
+ "</b>"));
} catch (Exception e) {
// Check log for login errors
Log.e("Twitter Login Error", "> " + e.getMessage());
}
/*
* Intent i = new Intent(this,ShareActivity.class);
* startActivity(i);
*/
}
}
}// oncreate.
private void loginToTwitter() {
// Check if already logged in
if (!isTwitterLoggedInAlready()) {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
Configuration configuration = builder.build();
TwitterFactory factory = new TwitterFactory(configuration);
twitter = factory.getInstance();
try {
Log.e("clickkkkkkkkkkk:", "authoriseeeeeee");
requestToken = twitter
.getOAuthRequestToken(TWITTER_CALLBACK_URL);
this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
.parse(requestToken.getAuthenticationURL())));
} catch (TwitterException e) {
e.printStackTrace();
}
} else {
Log.e("elseeeeeeeeeeeee:", "elseeeeeeee");
// user already logged into twitter
Toast.makeText(getApplicationContext(),
"Already Logged into twitter", Toast.LENGTH_LONG).show();
btnLoginTwitter.setVisibility(View.GONE);
btnLoginFaceBook.setVisibility(View.GONE);
// Getting user details from twitter
// For now i am getting his name only
Uri uri = getIntent().getData();
if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
// oAuth verifier
String verifier = uri
.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
try {
// Get the access token
accessToken = twitter.getOAuthAccessToken(requestToken,
verifier);
// Shared Preferences
Editor e = mSharedPreferences.edit();
// After getting access token, access token secret
// store them in application preferences
e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
e.putString(PREF_KEY_OAUTH_SECRET,
accessToken.getTokenSecret());
// Store login status - true
e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
e.commit(); // save changes
Log.e("Twitter OAuth Token", "> " + accessToken.getToken());
long userID = accessToken.getUserId();
Log.e("user id:", "" + userID);
User user = twitter.showUser(userID);
String username = user.getName();
Log.e("user name:", username);
// Hide login button
btnLoginTwitter.setVisibility(View.GONE);
// Displaying in xml ui
lblUserName.setText(Html.fromHtml("<b>Welcome " + username
+ "</b>"));
} catch (Exception e) {
// Check log for login errors
Log.e("Twitter Login Error", "> " + e.getMessage());
}
/*
* Intent i = new Intent(this,ShareActivity.class);
* startActivity(i);
*/
}
}
}// login
And this is the posting tweet:
class updateTwitterStatus extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Updating to twitter...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Places JSON
* */
protected String doInBackground(String... args) {
Log.d("Tweet Text", "> " + args[0]);
Log.e("Tweet Text", "> " + args[0]);
String status = args[0];
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.d("Status", "> " + response.getText());
Log.e("Status", "> " + response.getText());
} catch (TwitterException e) {
// Error in updating status
Log.d("Twitter Update Error", e.getMessage());
}
return null;
}
/**
* After completing background task Dismiss the progress dialog and show
* the data in UI Always use runOnUiThread(new Runnable()) to update UI
* from background thread, otherwise you will get error
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
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("");
}
});
}
}//update.
private void logoutFromTwitter() {
// Clear the shared preferences
Editor e = mSharedPreferences.edit();
e.remove(PREF_KEY_OAUTH_TOKEN);
e.remove(PREF_KEY_OAUTH_SECRET);
e.remove(PREF_KEY_TWITTER_LOGIN);
e.commit();
// After this take the appropriate action
// I am showing the hiding/showing buttons again
// You might not needed this code
btnLogoutTwitter.setVisibility(View.GONE);
btnUpdateStatus.setVisibility(View.GONE);
txtUpdate.setVisibility(View.GONE);
lblUpdate.setVisibility(View.GONE);
lblUserName.setText("");
lblUserName.setVisibility(View.GONE);
btnLoginFaceBook.setVisibility(View.VISIBLE);
btnLoginTwitter.setVisibility(View.VISIBLE);
}
private boolean isTwitterLoggedInAlready() {
// return twitter login status from Shared Preferences
return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
}
protected void onResume() {
super.onResume();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK))
{
//Log.e("this is","default back button..............");
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
return false;
}
This is my code.Please help me where i have done mistake and this my xml code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/back"
android:layout_alignParentLeft="true"
android:text="back"
/>
</RelativeLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<Button android:id="#+id/btnLoginFaceBook"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Login with facebook"
android:layout_marginLeft="10dip"
android:layout_marginRight="10dip"
android:layout_marginTop="30dip"/>
<!-- Twitter Login Button -->
<Button android:id="#+id/btnLoginTwitter"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Login with Twitter"
android:layout_marginLeft="10dip"
android:layout_marginRight="10dip"
android:layout_marginTop="30dip"/>
<!-- user name label -->
<TextView android:id="#+id/lblUserName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dip"
android:layout_marginTop="30dip"/>
<!-- label update status -->
<TextView android:id="#+id/lblUpdate"
android:text="Update Status"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:layout_marginRight="10dip"
android:visibility="gone"/>
<!-- Tweet EditText -->
<EditText android:id="#+id/txtUpdateStatus"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="10dip"
android:visibility="gone"/>
<!-- Tweet Button -->
<Button android:id="#+id/btnUpdateStatus"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Tweet"
android:layout_marginLeft="10dip"
android:layout_marginRight="10dip"
android:visibility="gone"/>
<!-- Twitter Logout button -->
<Button android:id="#+id/btnLogoutTwitter"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Logout from Twitter"
android:layout_marginLeft="10dip"
android:layout_marginRight="10dip"
android:layout_marginTop="50dip"
android:visibility="gone"/>
</LinearLayout>
</LinearLayout>
Use this code. It's production code from an app of mine. I fetch 2 values for Strings TWITTER_CONSUMER_KEY and TWITTER_CONSUMER_SECRET from my strings.xml file. While the values for Strings twit_access_token and twit_access_token_secret are pulled in from my SharedPreferences file. Replace those bits with your own method of storage.
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
// GET THE CONSUMER KEY AND SECRET KEY FROM THE STRINGS XML
String TWITTER_CONSUMER_KEY = getActivity().getString(R.string.TWITTER_CONSUMER_KEY);
String TWITTER_CONSUMER_SECRET = getActivity().getString(R.string.TWITTER_CONSUMER_SECRET);
// TWITTER ACCESS TOKEN
String twit_access_token = twitPrefs.getString(PREF_KEY_OAUTH_TOKEN, null);
// TWITTER ACCESS TOKEN SECRET
String twit_access_token_secret = twitPrefs.getString(PREF_KEY_OAUTH_SECRET, null);
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
builder.setOAuthAccessToken(twit_access_token);
builder.setOAuthAccessTokenSecret(twit_access_token_secret);
builder.setJSONStoreEnabled(true);
builder.setIncludeEntitiesEnabled(true);
builder.setIncludeMyRetweetEnabled(true);
builder.setIncludeRTsEnabled(true);
AccessToken accessToken = new AccessToken(twit_access_token, twit_access_token_secret);
Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
Paging paging = new Paging(200); // MAX 200 IN ONE CALL. SET YOUR OWN NUMBER <= 200
statuses = twitter.getHomeTimeline(paging);
try {
String strInitialDataSet = DataObjectFactory.getRawJSON(statuses);
JSONArray JATweets = new JSONArray(strInitialDataSet);
for (int i = 0; i < JATweets.length(); i++) {
JSONObject JOTweets = JATweets.getJSONObject(i);
Log.e("TWEETS", JOTweets.toString());
}
} catch (Exception e) {
// TODO: handle exception
}
} catch (Exception e) {
// TODO: handle exception
}
NOTE 1: The statuses is an instance of List<Status> statuses = new ArrayList<Status>(); that I have declared and instantiated as a global instance.
NOTE 2: This attribute is necessary builder.setJSONStoreEnabled(true); if you want the result to be in the JSON format. If you need it without JSON, let me know.
FINAL UPDATE:
After testing the OP's entire code and debugging literally everything in a test application, the culprit turns out to be a single line (well, actually, 2):
Paging paging = new Paging(200); // MAX 200 IN ONE CALL. SET YOUR OWN NUMBER <= 200
statuses = twitter.getHomeTimeline(paging);
Turns out, for some reason, the Twitter API does not like the Paging paging = new Paging(200);. Changing that to Paging paging = new Paging(10); strangely enough, gave me 20 tweets. Removing the Paging.... line entirely, gave me 19. Weird result really. But my best guess at this time is that the application is perhaps new on the Twitter developer network (it still shows during authentication that the app cannot access Direct Messages).
Change that part to:
// Paging paging = new Paging(10);
statuses = twitter.getHomeTimeline();

Categories

Resources