Twitter oauth with volley - java

I want to create an app that can post tweets to my twitter account.
I'm very new to coding and android so I'm struggling a lot here.
I can get a successful response using postman so i know my twitter API keys and secrets etc are correct.
But my question is. How do I take that postman request and turn it into something android can send.
Here's my first attempt.
I guess I'm not passing the tokens correctly?
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private TextView post_reponse_text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button post_request_button=findViewById(R.id.test);
post_reponse_text=findViewById(R.id.get_response_data);
post_request_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
postRequest();
}
});
}
private void postRequest(){
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
String url="https://api.twitter.com/1.1/statuses/user_timeline.json";
StringRequest stringRequest=new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
post_reponse_text.setText("Post Data : " +response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
post_reponse_text.setText("Post Data : Failed");
}
}){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap <String, String>();
params.put("screen_name", "realnamehere");
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("API Key", "placerealtokenshere");
params.put("API Secret", "placerealtokenshere");
params.put("TWITTER_ACCES_TOKEN", "placerealtokenshere");
params.put("TWITTER_ACCES_TOKEN_SECRET", "placerealtokenshere");
return params;
}
};
queue.add(stringRequest);
}
}
Below is the curl request as supplied by twitter. How so i code that up?
curl --request POST \
--url 'https://api.twitter.com/1.1/statuses/update.json?status=Hello%20world' \
--header 'authorization: OAuth oauth_consumer_key="CONSUMER_API_KEY", oauth_nonce="OAUTH_NONCE", oauth_signature="OAUTH_SIGNATURE", oauth_signature_method="HMAC-SHA1", oauth_timestamp="OAUTH_TIMESTAMP", oauth_token="ACCESS_TOKEN", oauth_version="1.0"' \

Related

How can I solve the register button to pass the form to mysql database and direct me to login page on android studio using java?

I have started mobile app programming using java on android studio, I created a login and register activity for the user and the backend using PHP MySQL to save the details and retrieve them while logging in. When testing register to fill the form and click the button it does not do anything. At first, it brought the error "volley timeout error and I fixed it using the retry policy and fixed the post variables in PHP. But still, it doesn't show any error nor direct me to login page or no changes in the database.
I tried to change the URL from my PC's IP to the emulator's and the server database address but to no avail. I've tried to see what is the error but I'm going through circles. my xamp is also running. I have tried to debug the login activity first and by that, I'll be able to know what error occurs there
Register Activity
package com.example.artisanapplication;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.HashMap;
import java.util.Map;
public class RegisterActivity extends AppCompatActivity {
TextView loglink;
private EditText etid, etname, etmob, etpassword, etpassword2, etemail;
private TextView tvStatus;
private Button btnregister;
private String URL = "http://192.168.0.13:8080/artisan_system/register.php";
private String id, fname, mobileno, password, reenterpass, email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
etid = findViewById(R.id.etid);
etname = findViewById(R.id.etname);
etmob = findViewById(R.id.etmob);
etpassword = findViewById(R.id.etpassword);
etpassword2 = findViewById(R.id.etpassword2);
etemail = findViewById(R.id.etemail);
tvStatus = findViewById(R.id.tvStatus);
btnregister = findViewById(R.id.btnregister);
id = fname = mobileno = password = reenterpass = email = "";
loglink = findViewById(R.id.loginlink);
}
public void save(View view) {
id = etid.getText().toString().trim();
fname = etname.getText().toString().trim();
mobileno = etmob.getText().toString().trim();
password = etpassword.getText().toString().trim();
reenterpass = etpassword2.getText().toString().trim();
email = etemail.getText().toString().trim();
if(!password.equals(reenterpass)) {
Toast.makeText(this, "Password should be the same", Toast.LENGTH_SHORT).show();
}
else if(!id.equals("") && !fname.equals("") && !mobileno.equals("") && !password.equals("") && !email.equals("")) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.equals("success")) {
tvStatus.setText("Successfully registered");
btnregister.setClickable(false);
} else if (response.equals("failure")) {
tvStatus.setText("Something went wrong!");
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.toString().trim(), Toast.LENGTH_SHORT).show();
}
}){
#Nullable
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> data = new HashMap<>();
data.put("id", id);
data.put("fname",fname );
data.put("mobileno",mobileno );
data.put("password", password);
data.put("email",email);
return data;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
}
public void login(View view) {
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
finish();
}
}
Register.php
<?php
if(isset($_POST['id']) && isset($_POST['fname']) && isset($_POST['mobileno']) && isset($_POST['password']) && isset($_POST['email'])) {
require_once "connection.php";
require_once "validate.php";
$id = validate($_POST['id']);
$fname = validate($_POST['fname']);
$mobileno = validate($_POST['mobileno']);
$password = validate($_POST['password']);
$email = validate($_POST['email']);
$sql = "insert into register values('$id', '$fname', '$mobileno', '" . md5($password) . "', '$email')";
echo $sql;
if(!$conn->query($sql)) {
echo "Failure";
} else {
echo "Success";
}
}
?>
login activity
package com.example.artisanapplication;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
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.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.HashMap;
import java.util.Map;
public class LoginActivity extends AppCompatActivity {
TextView forgetbtn;
Button login;
private EditText etid, etpassword;
private String id, password;
private String URL = "https://10.0.2.2/artisan_system/login.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
id = password = "";
forgetbtn = findViewById(R.id.forgetbtn);
etid = findViewById(R.id.id_no);
etpassword = findViewById(R.id.password);
forgetbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(LoginActivity.this, ForgotPassActivity.class);
startActivity(i);
}
});
}
public void login(View view) {
id = etid.getText().toString().trim();
password = etpassword.getText().toString().trim();
if(!id.equals("") && !password.equals("")) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("res", response);
//if response state succes then create an intent object and launch success with an intent
if (response.equals("success")) {
Intent intent = new Intent(LoginActivity.this, HomeScreen.class);
startActivity(intent);
finish();
}
else if(response.equals("failure")) {
Toast.makeText(LoginActivity.this, "Invalid login", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LoginActivity.this, error.toString().trim(), Toast.LENGTH_SHORT).show();
}
}){
#Nullable
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> data = new HashMap<>();
data.put("id", id);
data.put("password", password);
return data;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}else{
Toast.makeText(this, "Fields cannot be empty", Toast.LENGTH_SHORT).show();
}
}
public void register(View view) {
Intent intent = new Intent(this, RegisterActivity.class);
startActivity(intent);
finish();
}
}

how to pass header api key in volley

I am new to android and volley
I'm straggling with JSON path
spent a lot of time debugging this code but unfortunately could not find the bug, can someone help me find the issue in this code. I am not able to see data on the activity page
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class dailyshop extends AppCompatActivity {
private RecyclerView mRecycler;
private cardAdapter mCardAdapter;
private ArrayList<carditem> mCardList;
private RequestQueue mRequestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dailyshop);
mRecycler = findViewById(R.id.recycler_view);
mRecycler.setHasFixedSize(true);
mRecycler.setLayoutManager(new LinearLayoutManager(this));
mCardList = new ArrayList<>();
mRequestQueue = Volley.newRequestQueue(this);
parseJSON();
}
private void parseJSON(){
String url = "https://fortnite-api.theapinetwork.com/store/get";
final JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String itemName = jsonObject.getString("name");
String imageUrl = jsonObject.getString("background");
int vCount = jsonObject.getInt("cost");
mCardList.add(new carditem(imageUrl,itemName,vCount));
}
mCardAdapter = new cardAdapter(dailyshop.this, mCardList);
mRecycler.setAdapter(mCardAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}
){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Authorization", "mycode");
return params;
}
};
mRequestQueue.add(request);
}
}
I tried to use custom API without key in same JSON child and it worked
api json file
{
"lastUpdate":1563408000,
"language":"en",
"data":[
{
"itemId":"0ac5766-6f9355e-6575a4e-abaef79",
"lastUpdate":1563408000,
"store":{
"isFeatured":false,
"isRefundable":true,
"cost":"500",
"occurrences":1,
"isNew":true
},
"item":{
"name":"Glitter",
"description":"",
"type":"emote",
"rarity":"rare",
"costmeticId":null,
"images":{
"icon":"https://fortnite-public-files.theapinetwork.com/emote/a7eb82676b96bc1ff2129ee739d70d4a.png",
"featured":null,
"background":"https://fortnite-public-files.theapinetwork.com/image/0ac5766-6f9355e-6575a4e-abaef79.png",
"information":"https://fortnite-public-files.theapinetwork.com/image/0ac5766-6f9355e-6575a4e-abaef79/item.png"
},
"backpack":{
},
"obtained_type":"vbucks",
"ratings":{
"avgStars":4.18,
"totalPoints":614,
"numberVotes":147
}
}
},
{
"itemId":"d2e8284-fb06feb-ea3fbe3-c41fd8b",
"lastUpdate":1563408000,
"store":{
"isFeatured":false,
"isRefundable":true,
"cost":"800",
"occurrences":3,
"isNew":false
},
"item":{
"name":"Star Wand",
"description":null,
"type":"pickaxe",
"rarity":"rare",
"costmeticId":null,
"images":{
"icon":"https://fortnite-public-files.theapinetwork.com/pickaxe/e0907bc2a6058035c5bf96820da6c21f.png",
"featured":null,
"background":"https://fortnite-public-files.theapinetwork.com/image/d2e8284-fb06feb-ea3fbe3-c41fd8b.png",
"information":"https://fortnite-public-files.theapinetwork.com/image/d2e8284-fb06feb-ea3fbe3-c41fd8b/item.png"
},
"backpack":{
},
"obtained_type":"vbucks",
"ratings":{
"avgStars":4.07,
"totalPoints":789,
"numberVotes":194
}
}
},
{
"itemId":"eb00ead-bb56b45-05e52f8-2398d3a",
"lastUpdate":1563408000,
"store":{
"isFeatured":false,
"isRefundable":true,
"cost":"300",
"occurrences":1,
"isNew":true
},
"item":{
"name":"Scanline",
"description":"",
"type":"wrap",
"rarity":"uncommon",
"costmeticId":null,
"images":{
"icon":"https://fortnite-public-files.theapinetwork.com/wrap/5677d39e97ba5bf8d92e25bc520e7cc0.png",
"featured":null,
"background":"https://fortnite-public-files.theapinetwork.com/image/eb00ead-bb56b45-05e52f8-2398d3a.png",
"information":"https://fortnite-public-files.theapinetwork.com/image/eb00ead-bb56b45-05e52f8-2398d3a/item.png"
},
"backpack":{
},
"obtained_type":"vbucks",
"ratings":{
"avgStars":4.82,
"totalPoints":164,
"numberVotes":34
}
}
},
{
"itemId":"a784814-93b4ea3-3c26b6f-631fac7",
"lastUpdate":1563408000,
"store":{
"isFeatured":false,
"isRefundable":true,
"cost":"500",
"occurrences":1,
"isNew":true
}
}
]
}
I need help with JSON path and if there is something wrong with my code
Try this:
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
String credentials = "username" + ":" + "password";
String base64EncodedCredentials = Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
HashMap<String, String> headers = new HashMap<>();
headers.put("Authorization", "Basic " + base64EncodedCredentials);
return headers;
}

Run activity twice (instead of once) to get value from getter

When tapping an image (from a previous activity) I get to this activity (where I pass the clientid) that reads a JSONArray and use a setter to set the nick.
I then use a getter to do a textview setText.
The problem is that the first time no nick is set. When I go back to the previous activity and tap the same image again, only then the nick is set.
Why isn't the nick displayed from the first time.
(ps: I'm quite new to Java/Android Studio)
package com.smartvibes.smartbeat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class profileViewActivity extends AppCompatActivity {
RequestQueue rs;
String url, id, nick, age, city, mainpic, numpics, extrapic0, extrapic1, extrapic2, extrapic3, extrapic4, extrapic5;
TextView profileIntro;
static String pnick;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_view);
Bundle getProfileId = getIntent().getExtras();
if (getProfileId == null) {
return;
}
String profileid = getProfileId.getString("profileid");
url = "https://www.smartvibes.be/profiles/api/profileview.php?id=" + profileid;
rs = Volley.newRequestQueue(this);
sendjsonrequest();
profileIntro = (TextView) findViewById(R.id.profileIntro);
profileIntro.setText(getPnick());
}
public void sendjsonrequest() {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
setPnick(response.getString("nick"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
rs.add(jsonObjectRequest);
}
public static void setPnick(String nick) {
pnick = nick;
}
public static String getPnick(){
return pnick;
}
}
Because sendjsonrequest is an async call
You need to update textView in onResponse Method itself, like below
setPnick(response.getString("nick"));
profileIntro.setText(getPnick());

Get POST Result in JSON

I'm sending the data with the POST. I get the answer with JSON.
If I use plain text instead of JSON, it's working but It doesn't work with JSON.
I do not receive any error screen in the application
if (status) = true -> Register OK
IMPORT:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import javax.xml.transform.Result;
JSON:
[{"status":true,"result":"registerSuccessful","message":"Register succeeded"}]
JAVA Code:
private void registernewuser() {
StringRequest request = new StringRequest(Request.Method.POST, registerUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
String RegisterResultString = jsonResponse.getString("status");
if (RegisterResultString.equals("true")) {
Toast.makeText(getApplicationContext(), "Successfully Registered User", Toast.LENGTH_LONG).show();
Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "Sorry, Error Registering New User", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("registeruser", "true");
params.put("username", username.getText().toString().trim());
params.put("userpassword", userpassword.getText().toString().trim());
params.put("useremail", useremail.getText().toString());
return params;
}
};
Volley.newRequestQueue(this).add(request);
}
I'm not having trouble building applications. But I can't find my fault.
Your JSON code is a JSONArray with a single JSONObject because of square brackets. So, just set type of your jsonResponse as JSONArray and fetch a JSONObject using the JSONArray.getJSONObject(0) method.
JSONArray jsonResponse = new JSONArray(response);
String registerResultString = jsonResponse.getJSONObject(0).getString("status");
You need to add the header to your request to indicate the JSON usage :
request.addHeader("content-type", "application/json");
Else it will interpret it as plain text.
You can call the request as JSONRequest
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
your_url, new com.android.volley.Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
};

how to make volley request in loop until specific response come

How to make Volley request in loop until specific response come?
package raju.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.skyfishjy.library.RippleBackgroun;
public class xxx extends AppCompatActivity {
int xi= 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_xxx);
StringRequest sr = new StringRequest("http://reju.pe.hu/test.php", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.contains("1")){
xi=1;
}
Log.w("res",response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
while (xi==0){
try {
Thread.sleep(1000);
RequestQueue xx = Volley.newRequestQueue(this);
xx.add(sr);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Here I have created a method called runRequest, which has the code you've given above. The only changes I've made to the code is that I am waiting for the response to the request, checking if it's a specific response. If it's not the specific response, the method runRequest is called again, and if it's the specific response, nothing is done.
public void runRequest() {
StringRequest sr = new StringRequest("http://reju.pe.hu/test.php", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.contains("1")) {
//here comes the specific response
} else {
runRequest();
//re run the request
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue xx = Volley.newRequestQueue(this);
xx.add(sr);
}

Categories