I did a TCP client on Java and works fine, but when I import the class to my Android project, it doesn't work.
Android code:
// ...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.SEND);
ssid = (EditText) findViewById(R.id.textSsid);
pass = (EditText) findViewById(R.id.textPass);
debugText = (EditText) findViewById(R.id.debugText);
cliente = new ClienteTCP();
debugText.setText("Version 1-prealpha");
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Do something in response to button click
demo(v);
}
});
}
public void demo(View view) {
cliente.configure(ssid.getText(), pass.getText());
CharSequence cs = cliente.sendMessage("Hola Mundo");
if ( cs != null)
debugText.setText(cs);
else
debugText.setText("ERROR OCURRED");
}
// ...
I always get the "ERROR OCURRED" message, I try to use another IPs, but all of them works fine on Java and not on android.
The class code:
private CharSequence SSID, pass;
private String HOST = "52.28.45.92"; // My external server i tried with localhot server too ...
// of course i have a server aplication running hahaha
private int PORT = 5000;
private Socket s;
private DataOutputStream oms;
// ...
public CharSequence sendMessage(String ms) {
DataInputStream ims;
CharSequence data = null;
try {
s = new Socket(HOST,PORT);
oms = new DataOutputStream(s.getOutputStream());
ims = new DataInputStream(s.getInputStream());
oms.writeUTF(ms+getFull());
data = ims.readUTF();
oms.close();
ims.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
I think it can be due to my emulator, any ideas? is the code wrong?
EDIT: Server code:
# ...
# Wrote on Python:
while 1:
data = conn.recv(BUFFER_SIZE)
if not data: break
print "received data:", data
conn.send(data+'\r\n')
conn.close()
Related
I am trying to do A chat between clients(android) to a server with a socket connection. I want my client to be able to send messages to the server and at the same time to listen to messages that the server is sending back. I was able to do a thread that will do the connection and opens a thread that sends a message whenever the client presses a button but I don't know how to add a thread that will listen to server response.
here is my client code
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
TextView tv1;
Button btnSend;
EditText etMessage;
String message_data;
PrintWriter output;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = (TextView) findViewById(R.id.tv);
etMessage = (EditText) findViewById(R.id.et_message);
btnSend = (Button) findViewById(R.id.button_send);
doConnection("Idan", "uid2");
}
#Override
public void onClick(View v) {
if (v== btnSend)
{
message_data = etMessage.getText().toString();
new Thread(new ThreadSend(message_data)).start();
}
}
public class ThreadSend implements Runnable{
private String messageTOSend;
ThreadSend(String message){
this.messageTOSend = message;
}
#Override
public void run() {
output.write(messageTOSend);
output.flush();
}
}
Thread thread = new Thread(){
#Override
public void run() {
super.run();
try {
Socket s = new Socket("10.0.0.5", 7979);
output = new PrintWriter(s.getOutputStream());
String connection_data = "Idan//uid1";
output.write(connection_data);
output.flush();
output.write("Hello");
output.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
};
private void doConnection(String userUid, String destinationUid) {
thread.start();
btnSend.setOnClickListener(this);
}
}
can someone help me or give me any advice where I can find information about it
So I have been trying to make a feature in my app where I can login and then fetch data from my database through the Django REST Framework. My logging in works as it only uses POST, but retrieving items does not work.
For some reason my AsyncTask does not get called for retrieving posts.
I have placed my AsyncTask for both activities, which are login and posts, on a separate java file only for handling Web Server stuff.
I am wondering if this is because I should put AsyncTask on each activities.
login.java
public class Login extends AppCompatActivity {
Button LoginButton;
EditText uUserName, uPassWord;
WSAdapter.SendAPIRequests AuthHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//SetupHomeBtn = (ImageButton) findViewById(R.id.SetupHomeBtn);
LoginButton = (Button) findViewById(R.id.LoginButton);
uUserName = (EditText) findViewById(R.id.LoginUserBox);
uPassWord = (EditText) findViewById(R.id.LoginPassBox);
//AuthHelper = new WSAdapter().new SendDeviceDetails();
// Moves user to the main page after validation
LoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// gets the username and password from the EditText
String strUserName = uUserName.getText().toString();
String strPassWord = uPassWord.getText().toString();
// API url duh
String APIUrl = "http://192.168.0.18:8000/token-auth/";
// If the user is authenticated, then transfer to the MainActivity page
if (APIAuthentication(strUserName, strPassWord, APIUrl)){
startActivity(new Intent(Login.this, Posts.class));
}
}
});
}
private boolean APIAuthentication(String un, String pw, String url){
// when it wasn't static -> AuthHelper = new WSAdapter().new SendAPIRequests();
AuthHelper = new WSAdapter.SendAPIRequests();
JSONObject postData = new JSONObject();
try {
// Attempt to input info to the Django API
postData.put("username", un);
postData.put("password", pw);
// Putting the data to be posted in the Django API
AuthHelper.execute(url, postData.toString());
return true;
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
}
posts.java
public class Posts extends AppCompatActivity {
TextView postsSect;
Button postsDoneBtn;
WSAdapter.SendAPIRequests PostsHelper;
StringBuilder postsBuffer = new StringBuilder();
#Override
protected void onResume(){
super.onResume();
PostsDetails postDetailsHelper = new PostsDetails();
postDetailsHelper.ListPosts();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_posts);
PostsDetails postDetailsHelper = new PostsDetails();
postsDoneBtn = (Button) findViewById(R.id.PostsDoneButton);
postDetailsHelper.callPostDetails("192.168.0.18:8000/api");
postDetailsHelper.ListPosts();
postDetailsHelper.postDetailsCalled('n');
postsDoneBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Posts.this, MainActivity.class));
}
});
}
public class PostsDetails {
//String post_title, post_content;
ArrayList<Integer> post_id = new ArrayList<Integer>();
ArrayList<String> post_title = new ArrayList<String>();
ArrayList<String> post_content = new ArrayList<String>();
boolean isPDCalled;
// sets if Post details are called
boolean postDetailsCalled(char called) {
if (called == 'y'){
return true;
}
return false;
}
// checks if postsDetails functions are called for AsyncTask
boolean getIsPDCalled(){
return isPDCalled;
}
// calls the execute for AsyncTask
private void callPostDetails(String theurl){
PostsHelper = new WSAdapter.SendAPIRequests();
// sets if post details are called
postDetailsCalled('y');
// executes AsyncTask
PostsHelper.execute(theurl);
}
// sets values for the posts arrays
public void setPost(int p_id, String p_title, String p_content) {
post_id.add(p_id);
post_title.add(p_title);
post_content.add(p_content);
}
// Lists the posts from the database
public void ListPosts() {
/////////// add functionality if a post was deleted and was clicked
postsSect = (TextView) findViewById(R.id.PostsSection);
postsSect.setText(post_title.get(post_title.size()) + "\n");
for (int i = post_id.size() - 1; i > 0; i--)
{
postsSect.append(post_title.get(i));
}
}
}
}
WSAdapter.java
// I forgot what WS stands for, but this class serves as an adapter for JSON and Online stuff
// I think it stands for With-Server Adapter
public class WSAdapter extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
static public class SendAPIRequests extends AsyncTask<String, String, String> {
// Add a pre-execute thing
#Override
protected String doInBackground(String... params) {
Log.e("TAG", params[0]);
Log.e("TAG", params[1]);
String data = "";
HttpURLConnection httpURLConnection = null;
try {
// Sets up connection to the URL (params[0] from .execute in "login")
httpURLConnection = (HttpURLConnection) new URL(params[0]).openConnection();
// Sets the request method for the URL
httpURLConnection.setRequestMethod("POST");
// Tells the URL that I am sending a POST request body
httpURLConnection.setDoOutput(true);
// To write primitive Java data types to an output stream in a portable way
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
// Writes out a byte to the underlying output stream of the data posted from .execute function
wr.writeBytes("postData=" + params[1]);
// Flushes the postData to the output stream
wr.flush();
wr.close();
// Representing the input stream
InputStream in = httpURLConnection.getInputStream();
// Preparing input stream bytes to be decoded to charset
InputStreamReader inputStreamReader = new InputStreamReader(in);
StringBuilder dataBuffer = new StringBuilder();
// Translates input stream bytes to charset
int inputStreamData = inputStreamReader.read();
while (inputStreamData != -1) {
char current = (char) inputStreamData;
inputStreamData = inputStreamReader.read();
// concatenates data characters from input stream
dataBuffer.append(current);
}
data = dataBuffer.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
// Disconnects socket after using
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
Log.e("TAG", data);
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// expecting a response code fro my server upon receiving the POST data
Log.e("TAG", result);
Posts.PostsDetails postsHelper = new Posts().new PostsDetails();
// For posts
try {
if (postsHelper.getIsPDCalled()){
JSONObject pJObj = new JSONObject(result);
JSONArray pJObjArray = pJObj.getJSONArray("posts");
for (int i = 0; i < pJObjArray.length(); i++) {
JSONObject pJObj_data = pJObjArray.getJSONObject(i);
postsHelper.setPost(pJObj_data.getInt("id"), "post_title", "post_content");
}
}
} catch (JSONException e) {
//Toast.makeText(JSonActivity.this, e.toString(), Toast.LENGTH_LONG).show();
Log.d("Json","Exception = "+e.toString());
}
}
}
}
Yes, you can and should put the network calls functions in a separate java file for better readability and test-coverage.
Apart from that, i would suggest to use Retrofit as your HTTP client. It helps you to manage all the dirty things like headers and converters etc, so you can put all your effort on your logic and implementing your callback actions.
Here I created a fan activity and every time when I Click to any button
It Start Fan-Socket class and create a new Socket on every click button.
But I am getting a delay when I Click buttons continueosly.
how can I Send a multiple request using single Socket and on each button
click how can I send a msg string through the Socket??
Is there is Something that creating a buffer and putting a value in
that buffer and call each buffer value on every click.
if it so How can I do that.. ??
Kindly help me to solve this issue as
I am new in android programming I can not able to solve this problem
from several day
Fan Activity:
public class FAN extends AppCompatActivity {
private Button buttonOn;
private Button button1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(layout.activity_fan);
buttonOn = (Button) findViewById(id.Buttonon);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
buttonOn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (turnOn) {
int tmpInt = 2;
String FAN = String.valueOf(tmpInt); //Converting int to string.
FAN_SOCKET b1 = new FAN_SOCKET(); // calling class fan socket
b1.execute(FAN); //calling fan-socket class and pass the the 2 value through it.
turnOn = false;
}
else {
int tmpInt = 0;
String FAN = String.valueOf(tmpInt); //Converting int to string.
FAN_SOCKET b1 = new FAN_SOCKET(); // calling class fan socket
b1.execute(FAN); //sending value to socket.
turnOn = true;
}
}
});
Fan-Socket Class:
class FAN_SOCKET extends AsyncTask<String,Void,String>{
Socket socket = null;
PrintWriter pw;
String response;
#Override
protected String doInBackground(String... voids) {
String massage = null;
try {
massage = voids[0];
socket = new Socket("192.168.0.79",8888 );
pw = new PrintWriter(socket.getOutputStream());
pw.write(massage);
try {
pw.flush();
pw.close();
socket.close();
} catch (SocketException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
i have a problem with android application that contain a AsyncTask. When i try to debug it androidStudio bring me to a section of comments of asynctask. i don't understand if this problem is caused by problem on library or if the problem is on the logic of costruction: i have a class that
-fetch an integer from UI then
-lunch asynctask that connect to a server and receive the data (put its on a variable), then
-redraw the ui and set out the data on a textview
like the code:
public class MainActivity extends Activity
{
LinearLayout spazioGen;
TextView[] cell;
LinearLayout[] rows;
LinearLayout def;
LinearLayout solution;
private Socket client;
private PrintWriter printwriter;
private BufferedReader in;
private EditText textField;
private TextView serverOut;
private Button button;
private String messsage;
private String inputLine;
private Integer dimensionChoosed = 10;
private String word1 = "";
private String word2 = "";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textField = (EditText) findViewById(R.id.dimension);
button = (Button) findViewById(R.id.findCenter);
button.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
messsage = textField.getText().toString(); // get the text message on the text field
textField.setText(""); // Reset the text field to blank
dimensionChoosed = Integer.parseInt(messsage.toString());
SendMessage sendMessageTask = new SendMessage();
sendMessageTask.execute();
createGriglia();
}
});
}
private void createGriglia(Integer dimensionChoosed)
{
int i,j;
spazioGen = new LinearLayout(this);
spazioGen.setOrientation(LinearLayout.VERTICAL);
spazioGen.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
spazioGen.setBackgroundDrawable(getResources().getDrawable(R.drawable.border_ext));
spazioGen.setPadding(5, 5, 5, 5);
//create an array of textview to fillup with data received from server
setContentView(spazioGen);
}
private class SendMessage extends AsyncTask<Void, Void, Void>
{
#Override
protected Void doInBackground(Void... params)
{
try
{
client = new Socket("192.168.0.104", 4444); // connect to the server
printwriter = new PrintWriter(client.getOutputStream(), true);
printwriter.println(messsage); // write the message to output stream
printwriter.flush();
InputStreamReader inputStreamReader = new InputStreamReader(client.getInputStream());
BufferedReader bufferedReader = new BufferedReader(inputStreamReader); // get the client message
String message = "";
while ((message = bufferedReader.readLine()) != null && !(message.equals("flag")))
{
word1 = message;
//do stuff with data received
}
while ((message = bufferedReader.readLine()) != null)
{
word2 = message;
//do stuff with data received
}
inputStreamReader.close();
System.out.println(message);
printwriter.close();
client.close(); // closing the connection
} catch (UnknownHostException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid)
{
createGriglia(dimensionChoosed);
}
}
}
Thanks in advance
thanks to everybody who helps me.
I solved this problem installing latest version of android studio.
I hope this can help who got my same problem
I have an HTTP GET that is receiving information from a URI. The URI is for Google Shopping.
https://www.googleapis.com/shopping/search/v1/public/products?key=key&country=US&q=digital+camera&alt=atom
(Left my key out).
Is there a way that I can change it from
q=digital+camera
to anything a user puts in an EditText?
So basically, I want the EditText to change what is searched on Google Shopping.
First screen, ProductSearchEntry with EditText for search query:
Code for ProductSearchEntry
public class ProductSearchEntry extends Activity{
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.productsearchentry);
Button search = (Button) findViewById(R.id.searchButton);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent searchIntent = new Intent(getApplicationContext(), ProductSearch.class);
startActivity(searchIntent);
}
});
}
}
Then, I have a second class, ProductSearch, with no picture, but just this code:
public class ProductSearch extends Activity{
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.productsearchresults);
EditText searchQuery = (EditText) findViewById(R.id.searchQuery);
ProductSearchMethod test = new ProductSearchMethod();
String entry;
TextView httpStuff = (TextView) findViewById(R.id.httpTextView);
try {
entry = test.getSearchData(searchQuery.getText().toString());
httpStuff.setText(entry);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Which references the ProductSearchMethod class which consists of a TextView that is changed to the code recieved in the HTTP GET:
Code:
public class ProductSearchMethod {
public String getSearchData(String query) throws Exception{
BufferedReader in = null;
String data = null;
try{
HttpClient client = new DefaultHttpClient();
URI site = new URI("https://www.googleapis.com/shopping/search/v1/public/products?key=key&country=US&q="+query.replace(" ","+")+"&alt=atom");
HttpGet request = new HttpGet();
request.setURI(site);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String l = "";
String nl = System.getProperty("line.seperator");
while((l = in.readLine()) !=null){
sb.append(l + nl);
}
in.close();
data = sb.toString();
return data;
}finally{
if (in != null){
try{
in.close();
return data;
}catch (Exception e){
e.printStackTrace();
}
}
}
}
}
ProductSearchMethod comes up great, but it doesn't change the text from "Loading Items" to the website code. I had it working before but then I tried to edit what it searched (all this ^) and now it doesn't change.
Make changes in your code like
public class ProductSearchEntry extends Activity{
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.productsearchentry);
EditText etSearch = (EditText) findViewById(id of your edittext);
Button search = (Button) findViewById(R.id.searchButton);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//while calling intent
Intent searchIntent = new Intent(getApplicationContext(), ProductSearch.class);
searchIntent.putExtra("searchText",etSearch.getText().toString());
startActivity(searchIntent);
}
});
}
}
and another activity like this,
public class ProductSearch extends Activity{
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.productsearchresults);
String searchQuery = getIntent().getStringExtra("searchText");
ProductSearchMethod test = new ProductSearchMethod();
String entry;
TextView httpStuff = (TextView) findViewById(R.id.httpTextView);
try {
entry = test.getSearchData(searchQuery);
httpStuff.setText(entry);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Yeah... Change your getSearchData() method to include a string as a parameter
public String getSearchData(String query) throws Exception{
Then, insert that string into the query URL, replacing spaces with "+". You may want to do further conditioning to the string, for instance URL encoding it.
URI site = new URI("https://www.googleapis.com/shopping/search/v1/public/products?key=key&country=US&q="+query.replace(" ","+")+"&alt=atom");
In your XML, create a button that contains the following line:
android:onClick="search"
In your ProductSearch activity, add the following method, and move the code in onCreate into it. You will also need to create an EditText in your XML for input.
public void search(View v)
{
EditText searchQuery = (EditText) findViewById(R.id.searchQuery);
ProductSearchMethod test = new ProductSearchMethod();
String returned;
try {
returned = test.getSearchData(searchQuery.getText().toString());
httpStuff.setText(returned);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Finally, you will probably want to read up on running asynchronous tasks so that the query won't freeze your app while performing.
May be I got you wrong, but why don't you just pass it as a parameter in
getSearchData() => getSearchData(string query)
Then you can change the line
URI site = new URI("https://www.googleapis.com/shopping/search/v1/public/products?key=key&country=US&q=digital+camera&alt=atom");
to
URI site = new URI("https://www.googleapis.com/shopping/search/v1/public/products?key=key&country=US&q=+ URLEncoder.encode(query, "UTF-8")+&alt=atom");
Check out http://androidforums.com/developer-101/528924-arduino-android-internet-garage-door-works-but-could-use-input.html I use Asynctask to trigger a get command on a local Arduino server. It appends the Arduino's pin number and, depending on if it's needed, a port number to the end of the URL. I'm sure you could use it to help you out.