How can i pass data from class to another class? - java

I am doing in this code: message receiving,filtering and getting then sending data to a sql server. I need the category_id from mysql database. Then i will use it in CallAPI as ide . I took the data from my mysql database but i couldn't transfer the data one class to another. So how can i transfer the data from one class to another?
I solved my problem and updated it i hope it can help to another peoples.
my smsCame codes:
package com.pvalid.api;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.Request;
import okhttp3.Response;
public class smsCame extends BroadcastReceiver {
private static final String TAG = "MyBroadcastReceiver";
#Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG , "SMS RECEIVEDD");
Bundle bundle = intent.getExtras();
Object[] pdus = (Object[]) bundle.get("pdus");
String format = intent.getExtras().getString("format");
SmsMessage message = SmsMessage.createFromPdu((byte[]) pdus[0], format);
String messagea = message.getOriginatingAddress();
String messagesb = message.getMessageBody();
Boolean messagee= messagesb.substring(0, 8).matches("(G-)\\d\\d\\d\\d\\d\\d");
String Code = messagesb.substring(2, 8);
String ide;
String usercode = "Admin";
//i need to POST this lmessage to my php server when sms received
//property is has to be Code:lmessage
// i have a receiver in my url when isset($_POST['Code'])
if (messagee){
try{
ide = new heyAPI(usercode).execute().get();
new CallAPI(usercode, Code, ide).execute();}
catch(Exception e){
ide="11";
new CallAPI(usercode, Code, ide).execute();
}
}
else{
Log.i(TAG,"Didnt match");}
}
private static class heyAPI extends AsyncTask<String, String, String> {
private final OkHttpClient client = new OkHttpClient();
String usercodes;
private heyAPI(String usercode){
usercodes= usercode;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
RequestBody formBody = new FormBody.Builder()
.add("usercode", usercodes) // A sample POST field
.build();
Request request = new Request.Builder()
.url("url-here")
.post(formBody)
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
Headers responseHeaders = response.headers();
String elem_id= response.body().string();
return elem_id;
}
catch (Exception e){
Log.i(TAG,"Error:"+e);
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
private static class CallAPI extends AsyncTask<String, String, String> {
String emailString;
String commentString;
String id;
private CallAPI(String usercode, String Code,String ide){
emailString = usercode;
commentString = Code;
id=ide;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
OkHttpClient client = new OkHttpClient();
RequestBody formBody = new FormBody.Builder()
.add("usercode", emailString) // A sample POST field
.add("Code", commentString) // Another sample POST field
.add("category_id", id) // Another sample POST field
.build();
Request request = new Request.Builder()
.url("url here") // The URL to send the data to
.post(formBody)
.build();
try {
Response response = client.newCall(request).execute();
return response.body().string();
}catch(IOException e){
Log.i(TAG,"IO exception");
return "";
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
}

You can use transfer your data in different class by using database , shared preference and intents.
If You want to transfer data from class A to B by intent then
In class A
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
intent.putExtra("key_name", value);
startActivity(intent);
and In class B for getting the transferred data
Intent intent=new getIntent();
String s=intent.getExtras().getString("key_name");

hi you can send parameters class A to class B is so way...
you can use constructor like this
public class test {
public test(String p){...}
}
and you can use intent
you can use shared preference in
learn with this site Shared preference
save data from class A and read class B
and you must be careful because when you give data from server thread is different Ui thread !
private SharedPreferences mPreference;
mPreference = getSharedPreferences("Share", Context.MODE_PRIVATE);
// save data
mPreference.edit()
.putBoolean("test", category_id)
.apply();
// read data
mPreference.getString("test", defaultSTR);

Related

400 error code while using twitter search API

I am trying to query Twitter on my android app and retrieve all the tweets related to the keyword "AgilebizKE" using retrofit.
I am currently getting a 400 error code. After doing some research i have found that either my query parameters are wrong or my request isn't 'authorized'. However, i see no issues with my query parameters.
Main Activity relevant code:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.twitter.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
tweetAPI tweetapi = retrofit.create(tweetAPI.class);
Call<List<tweet>> call = tweetapi.getTweets();
call.enqueue(new Callback<List<tweet>>() {
#Override
public void onResponse(Call<List<tweet>> call, Response<List<tweet>> response) {
if (!response.isSuccessful()) {
tweets_results.setText("code: " + response.code());
return;
}
List<tweet> tweets = response.body();
for (tweet tweet : tweets){
String content = "";
content+="Created at: "+tweet.getCreated_at()+"\n";
content+="Text: "+tweet.getText()+"\n";
content+="Retweets: "+tweet.getRetweet_count()+"\n";
content+="Favs: "+tweet.getFavorite_count()+"\n\n";
tweets_results.append(content);
}
}
#Override
public void onFailure(Call<List<tweet>> call, Throwable t) {
tweets_results.setText(t.getMessage());
}
});
Interface
public interface tweetAPI {
#GET("1.1/search/tweets.json?q=AgilebizKE")
Call<List<tweet>> getTweets();
}
Tweet pojo
ublic class tweet {
private String created_at;
private String text;
private String retweet_count;
private String favorite_count;
public String getCreated_at() {
return created_at;
}
public String getText() {
return text;
}
public String getRetweet_count() {
return retweet_count;
}
public String getFavorite_count() {
return favorite_count;
}
}
Ok so i decided to switch to using twitter4j instead of retrofit since it is much easier and quicker. For more details on this go to this site: http://twitter4j.org/
I will now explain how i implemented twitter search functionality for my use case.
Android Manifest
Add these permissions
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.INTERNET" />
build.gradle(Module: app)
Add this
implementation files('libs/twitter4j-core-4.0.7.jar')
Next, you have to create a JobIntentService so as to run the network functions, that twitter4j requires, off the main thread. This is the video I used to better understand this concept: https://www.youtube.com/watch?v=B4gFbWnNpac&t=567s
TweetJobIntentService.java
Before proceeding any further, register your app and get its personal OAuth twitter credentials from the twitter for devs portal. Fill these credentials where I have indicated in the code sample below.
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.core.app.JobIntentService;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import java.util.ArrayList;
import java.util.List;
import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
public class TweetJobIntentService extends JobIntentService {
private static final String TAG = "TweetJobIntentService";
static void enqueueWork(Context context, Intent work) {
enqueueWork(context, TweetJobIntentService.class, 123, work);
}
#Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate: ");
}
#Override
protected void onHandleWork(#NonNull Intent intent) {
Log.d(TAG, "onHandleWork: ");
List tweets = new ArrayList();
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer("Your_OAuthConsumerKey", "Your_AuthConsumerSecret");
AccessToken accessToken = new AccessToken("Your_OAuthAccessToken", "Your_OAuthAccessTokenSecret");
twitter.setOAuthAccessToken(accessToken);
Query query = new Query(Your_search_Keyword);
try {
QueryResult result = twitter.search(query);
for (Status status : result.getTweets()) {
Log.d(TAG, status.getText());
}
if (isStopped()) return;
} catch (TwitterException e) {
e.printStackTrace();
}
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDeastroy");
}
#Override
public boolean onStopCurrentWork() {
Log.d(TAG, "onStopCurrentWork");
return super.onStopCurrentWork();
}
}
Your retrieved tweets should be printed in logcat.
Your Main activity/fragment
Here, you will initiate/call your JobIntentService. For me, my service is initiated in a fragment in the onViewCreated method. Yours can be initiated following a button click or whatever you wish.
Intent jobserviceIntent = new Intent(getActivity(), TweetJobIntentService.class);
TweetJobIntentService.enqueueWork(getActivity(), jobserviceIntent);

The php file is returning false instead of the bind values.How can I fix this?

I have an android studio project connected to a mysql online database, using php files.
The problem is I don't receive the parameters(idquestion, question, id) from the php file with a given idquestion and a category.
The class and the php file are a similar replica to ohers that works and yet is not working.
I tried the debugger and i find out that i pass the correct information (idquestion 1 and category "computers").
Also, i tried another php file with a different syntax just to print data and it worked, but that php file wasn't helpful in my class.
This is my php file
<?php
$con = mysqli_connect("localhost", "id8963226_user", "parola123", "id8963226_user");
$idquestion = #($_POST['idquestion']);
$category = #($_POST['category']);
$statement = mysqli_prepare($con, "select * from question where idquestion=? and category=?;");
mysqli_stmt_bind_param($statement, "is", $idquestion, $question);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $success, $idquestion, $question, $id);
$response = array();
$response["success"] = false;
while(mysqli_stmt_fetch($statement)){
$response["success"] = true;
$response["idquestion"] = $idquestion;
$response["question"] = $question;
$response["id"] = $id;
}
echo json_encode($response);
?>
These are my java classes
package com.example.allrateform;
import android.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class Question extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question);
//CREATING ALL INSTANCES FROM TEXTS
final TextView CategoryTextView = findViewById(R.id.CategoryTextView);
final TextView QuestionTextView = findViewById(R.id.QuestionTextView);
final TextView IdTextView = findViewById(R.id.IdTextView);
CategoryTextView.setText(Categories.Category);
final String category = CategoryTextView.getText().toString();
final int idquestion = 1;
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
String question = jsonResponse.getString("question");
int id = jsonResponse.getInt("id");
QuestionTextView.setText(question);
IdTextView.setText(id);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(Question.this);
builder.setMessage("Failed")
.setNegativeButton("Ok", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
//CREATING RESPONSE
ListRequest listRequest = new ListRequest(idquestion, category, responseListener);
RequestQueue queue = Volley.newRequestQueue(Question.this);
queue.add(listRequest);
}
}
package com.example.allrateform;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import java.util.HashMap;
import java.util.Map;
public class ListRequest extends StringRequest {
private static final String LIST_REQUEST_URL = "myUrl.com/myPhp.php";
private Map<String, String> params;
//METHOD TO PASS THE INFORMATION
public ListRequest(int idquestion, String category, Response.Listener<String> listener) {
super(Method.POST, LIST_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put("idquestion", idquestion + "");
params.put("category", category);
}
#Override
public Map<String, String> getParams() {
return params;
}
}
So again the project result is "Failed", meaning the php returns false.
If you have other ways to approach this it's ok as long as I'm able to store all the question from the "computer" categories in a java string array.
Feel free to ask any other questions about my database or other classes or anything.
Thank you in advance!
I got the problem.. it was a logic error in my php, binding ($statement, "is", $idquestion, $question) instead of ($statement, "is", $idquestion, $category) .. the given variables. Still, I don't how but i have another error now.
Look at the output
{"success":true,"idquestion":"Top programming languages?","question":"computers","id":1}
it was suppose to be
{"success":true,"idquestion":1,"question":"Top programming languages?","id":1}

Carrying and reusing information (json string) from an AsyncTask?

I have created a simple android app with 3 TextViews and then run an AsyncTask Task via a different class the next step would be to carry the information over and make the task reusable.
The Task will consume a String (URL) and the context of the MainActivity.
The Task will make a simple REST Request (GET) and retrieve a json string.
I have then created another class that which gets the json response and creates a .json file saves it to
..../0/Notes/launch.json
The folder "Notes is created by myself via file.mkdirs().
In the MainActivity I created an InputStream to read the .json file saved by the AsyncTask but once I try to open it, it gives me a FileNotFoundException.
Here's the code of my MainActivity.class
package com.example.root.example;
import android.Manifest;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.TextView;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 200);
String url = "https://api.spacexdata.com/v3/launches/upcoming"; //Copy the url and open it in your browser to see the json.
AsyncCall asyncCall = new AsyncCall(getApplicationContext());
asyncCall.myAsyncTask(url);
try {
InputStream inputStream = this.getAssets().open("launch.json");
int size = inputStream.available();
byte[] buffer = new byte[size];
inputStream.read(buffer);
inputStream.close();
String jsonStringFromFile= new String(buffer,"UTF-8");
JSONObject launchObject = new JSONObject(jsonStringFromFile);
System.out.println(launchObject.get("flight_number"));
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
This is the AsyncCall.class (making and retrieving the json etc..)
package com.example.root.example;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import java.io.IOException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class AsyncCall {
FileCreator fileCreator = new FileCreator();
private final Context myContext;
public AsyncCall(final Context context) {
myContext = context;
}
public void myAsyncTask(final String url) {
AsyncTask asyncTask = new AsyncTask() {
#Override
protected Object doInBackground(Object[] objects) {
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
Response response = null;
try {
response = okHttpClient.newCall(request).execute();
fileCreator.generateFile(myContext, myContext.getString(R.string.fileName), response.body().string());
} catch (IOException ioe) {
ioe.getMessage();
}
return null;
}
}.execute();
}
}
what am I trying to archive? I'm trying to save information (json here) and make it reusable just as the Falcon 9.
The issue lies in carrying information over to a different class.
If there's an alternative solution (other than saving a .json file) to fix this issue then please don't hesitate to post it.
This is just my first issue, the second issue appears once you open the api link and see that there are a few more than just one JSON String (0,1,2,3,4... upcoming missions).
I have no clue in any way to tacle the first let alone the second problem and have started over a few times, a while ago multiple times.
Within your Activity, you can get the JSON like so
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
okHttpClient.newCall(request).enqueue(new Callback() {
#Override
public void onResponse(Call call, final Response response) throws IOException {
try {
final String responseData = response.body().string();
JSONObject json = new JSONObject(responseData);
String flightNumber = json.getString("flight_number");
// TODO: Load number into a TextView
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Looking at your API response, though, you'll actually need new JSONArray(responseData), and you would have to loop over that to get each individual object's flight number

Android device connected to mysql server

I am currently working on a android app that needs to download everything from an online mySQL database, all of which will then be stored locally using the SQLite built into android.
The problem I am facing at the moment is making the connection from the android device to the server. I have not figured out how to pull information down yet.
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static android.content.ContentValues.TAG;
public class LoginWorker {
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> usersList;
private static String url_all_users = "http://localhost/get_user_login.php";
private static String TAG_SUCCESS = "success";
private static String TAG_USERS = "users";
private static String TAG_EMAIL = "email";
private static String TAG_PASSWORD = "password";
JSONArray users = null;
public void onCreate(){
System.out.print("Login worker onCreate started");
usersList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<>();
map.put("test","test");
usersList.add(map);
Log.d(TAG, "onCreate: LoadAllUsers Running now");
new LoadAllUsers().execute();
}
class LoadAllUsers extends AsyncTask<String, String, String>{
protected void onPreExecute(){
super.onPreExecute();
}
protected String doInBackground(String... args){
Log.d(TAG, "doInBackground: Start of method");
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(url_all_users, "GET", params);
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
users = json.getJSONArray(TAG_USERS);
for (int i = 0; i < users.length(); i++) {
JSONObject c = users.getJSONObject(i);
String password = c.getString(TAG_PASSWORD);
String email = c.getString(TAG_EMAIL);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_EMAIL, email);
map.put(TAG_PASSWORD, password);
usersList.add(map);
}
} else {
Log.d("doInBackground : ", "No user found");
}
}catch(JSONException e){
e.printStackTrace();
}
return null;
}
protected void onPostExecution(){}
}
This is an example of some of the code I have been working on (For the user login). Is there a simpler way to make this connection without having to use JSON and PHP? Any help will be greatly appreciated, even if it's just links to useful blogs or tutorials!
Follow these tutorials for connecting to mysql db and creating api which u can be used to retrieve data.
To Connect to db and create api:
https://www.simplifiedcoding.net/php-restful-api-framework-slim-tutorial-1/
https://www.simplifiedcoding.net/create-chat-app-for-android-using-gcm-1/
after creating api you can use retrofit to get data from api.
http://www.androidhive.info/2016/05/android-working-with-retrofit-http-library/

Android calling page that returns JSON error [duplicate]

This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 9 years ago.
I have a aspx page that I am calling from my android app that is returning JSON text but the java code below breaks here BufferedReader reader = new BufferedReader(new InputStreamReader(jc.getInputStream()));
with this error.
error android.os.NetworkOnMainThreadException
ARe you able to help plesae? Thanks
default.aspx return json
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.ContentType = "text/plain";
//Write the message
Response.Write("{'testvar':'testtext'}");
//End the response causing it to be sent
Response.End();
}
}
android java
public void connectWCF() {
try {
URL json = new URL("http://localhost:50851/Default.aspx");
URLConnection jc = json.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(jc.getInputStream()));
String line = reader.readLine();
reader.close();
} catch(Exception e){
}
links where I got the code ideas from
http://wyousuf.wordpress.com/2012/03/01/android-with-wcf-services/
http://matijabozicevic.com/blog/android-development/android-with-wcf-service
You are placing network communication on the main thread. You should use AsyncTask
http://developer.android.com/reference/android/os/AsyncTask.html
here's a nice video that explains JSON Parsing using AsyncTask.
http://www.youtube.com/watch?v=qcotbMLjlA4
For testing ONLY you can add the following in your Main Activity but it is consider bad practice.
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Since android 3.0, you can't put any calls to webpages or similar external resources in the main thread (in other words, any part of the activity) unless you do it with an AsyncTask, in order to avoid apps to look "locked" and unresponsive when waiting for a response from an external datasource. Therefore, you'll need to implement the webservice call with and AsyncTask.
Example class for AsyncTask:
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
public class cargaDatosRest extends AsyncTask<Context, Void, Void> {
private Context c;
private boolean resul = false;
private String control = "";
private String respStrS = "";
public cargaDatosRest(Context C)
{
c = C;
}
public String getStr()
{
return respStrS;
}
public String getControl()
{
return control;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//mProgressDialog.show();
}
#Override
protected Void doInBackground(Context... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpGet get = new HttpGet("url");
HttpResponse resp;
get.setHeader("content-type", "application/json");
try
{
/*resp contains the response from the webService. respStr and respJSON allows to read that resp in JSON format. Just delete them if you don't need them. You can asign the values returned by the webservice to local variables in the AsyncTask class and then read them with public methods, like the resul variable.*/
resp = httpClient.execute(getUsuarios);
String respStr = EntityUtils.toString(resp.getEntity());
JSONArray respJSON = new JSONArray(respStr);
this.resul = true;
}
catch(Exception ex)
{
Log.e("ServicioRest","Error!", ex);
this.resul = false;
}
}
public boolean getResul()
{
return this.resul;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC",progress[0]);
//mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(Void unused) {
//mProgressDialog.dismiss();
}
}
//calling the AsyncTask from the activity:
CargaDatosRest CallRest = new CargaDatosRest(this.getApplicationContext());
CallRest.execute();
Log.v("WebService", "Just trying "+arest.getResul());

Categories