I have a client socket which sends some lines (ANSI encoding) which forms a shape. The problem is that in the log cat, when i print out the lines, they form a complete shape, but in my Layout, textviews are not forming the shape even when they have the same length. I can see that the problem lies with the byte size of the space character. But since i can see it on the log cat, there must be a way to set the textviews to form a complete shape. I tried to replace all the space characters with and set the texts as an html form but still no luck. Is there a way that I'm missing?
class ClientThread implements Runnable {
private BufferedReader input;
#Override
public void run() {
// TODO Auto-generated method stub
try {
InetAddress servAddress = InetAddress.getByName(SERVER_IP);
socked = new Socket(servAddress, SERVERPORT);
input = new BufferedReader(new InputStreamReader(socked.getInputStream(), "windows-1252"));
while(!Thread.currentThread().isInterrupted()) {
String read = input.readLine();
updateConversationHandler.post(new updateUIThread(read));
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class updateUIThread implements Runnable {
String msg;
public updateUIThread (String str) {
this.msg = str;
}
#Override
public void run() {
// TODO Auto-generated method stub
TextView tv = new TextView(cont);
tv.setTextColor(Color.WHITE);
// tv.setText(makeTextWithColors(msg));
// tv.setText(msg + "count: " + msg.length());
tv.setText(msg);
screen.addView(tv);
scroller.post(new Runnable() {
public void run() {
scroller.smoothScrollTo(0, screen.getBottom());
}
});
}
}
It seems
tv.setTypeface(Typeface.MONOSPACE);
did the trick. It is a font that makes all characters with the same width.
TextView tb;
tb.setTextSize(20);
tb = Text View it will get floating point value of size you can put there integral type value
Related
This question already has an answer here:
What is the simplest way in Android to keep an objects value after every app run?
(1 answer)
Closed 7 years ago.
I have an android chat application that sends messages from client to server but I am looking for a way to store the send messages in some way, other than being displayed in the list.
Here is part of my application;
public class AndroidChatApplicationActivity extends Activity {
private Handler handler = new Handler();
public ListView msgView;
public ArrayAdapter<String> msgList;
// public ArrayAdapter<String> msgList=new ArrayAdapter<String>(this,
// android.R.layout.simple_list_item_1);;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
msgView = (ListView) findViewById(R.id.listView);
msgList = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1);
msgView.setAdapter(msgList);
// msgView.smoothScrollToPosition(msgList.getCount() - 1);
Button btnSend = (Button) findViewById(R.id.btn_Send);
receiveMsg();
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final EditText txtEdit = (EditText) findViewById(R.id.txt_inputText);
// msgList.add(txtEdit.getText().toString());
sendMessageToServer(txtEdit.getText().toString());
msgView.smoothScrollToPosition(msgList.getCount() - 1);
}
});
Button twitterButton = (Button) findViewById(R.id.website_Button);
twitterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendToWebsite();
}
});
}
protected void sendToWebsite() {
String url = "https://www.ljmu.ac.uk/";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
// receiveMsg();
// ----------------------------
// server msg receieve
// -----------------------
// End Receive msg from server//
public void sendMessageToServer(String str) {
final String str1 = str;
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
// String host = "opuntia.cs.utep.edu";
String host = "10.0.2.2";
String host2 = "127.0.0.1";
PrintWriter out;
try {
Socket socket = new Socket(host, 8008);
out = new PrintWriter(socket.getOutputStream());
// out.println("hello");
out.println(str1);
Log.d("", "test");
out.flush();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("", "test2");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("", "test3");
}
}
}).start();
}
public void receiveMsg() {
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
// final String host="opuntia.cs.utep.edu";
final String host = "10.0.2.2";
// final String host="localhost";
Socket socket = null;
BufferedReader in = null;
try {
socket = new Socket(host, 8008);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (true) {
String msg = null;
try {
msg = in.readLine();
Log.d("", "MSGGG: " + msg);
// msgList.add(msg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (msg == null) {
break;
} else {
displayMsg(msg);
}
}
}
}).start();
}
public void displayMsg(String msg) {
final String mssg = msg;
handler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
msgList.add(mssg);
msgView.setAdapter(msgList);
msgView.smoothScrollToPosition(msgList.getCount() - 1);
Log.d("", "Hi Test");
}
});
}
}
Could anyone suggest a method of storing the messages other than displaying them in a list?
You can try storing them in SharedPreferences. By what I gather, you want store the input so that you can later look at then in a different activity. Have a look at SharedPreferences here http://developer.android.com/reference/android/content/SharedPreferences.html
I am new to JSON and I was wondering how I would pull some info and put it into a JSON Object and then read some of the values. The json info looks like this,
{
"photos":{
"page":1,
"pages":1802,
"perpage":100,
"total":"180134",
"photo": [
{
"id":"8711964781",
"owner":"21156896#N07",
"secret":"3e24e45977",
"server":"8553",
"farm":9,
"title":"Old Harbor",
"ispublic":1,
"isfriend":0,
"isfamily":0
},
{
"id":"8712680696",
"owner":"21156896#N07",
"secret":"fe82f8387b",
"server":"8122",
"farm":9,
"title":"Rockefeller Plaza",
"ispublic":1,
"isfriend":0,
"isfamily":0
},
....
It photo array goes on for quite a while. How would I get the values of "isPublic"? "Secret" is a String because of the "" and isPublic is an integer or boolean? I basically have to put them into a URL link and download the image.
public class ReadString extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... FlickrString) {
try {
json = getValue();
return json.getString(FlickrString[0]);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
tvTest.setText(result);
}
This works for all the strings. How would I get the farm, isfriend, isfamily, and ispublic converted to a string? I tried something else now to get the Int values, I made a whole new class for reading the ints. But it isnt getting the correct int value. I have it download the int and I convert it to a string and then I change a textview to the string of the int using String.valueOf(x); What am i doing wrong?
public class ReadInt extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... FlickrString) {
try {
json = getValue();
int x = json.getInt(FlickrString[0]);
String y = String.valueOf(x);
return y;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
tvTest.setText(result);
}
}
Thanks!
JSONObject jobj = result.getJSONObject("photo");
jobj.getBoolean("ispublic");
jobj.getInt("isfriend");
The variable result is of typeJsonObject that should contain the entire object have pasted above in your code
Java is not like C++.In C++ 0 is false and other integers are true
I think you should create a function like this
private void boolean convertIntToBool(int value) {
if(value==0) {
return false;
} else {
return true;
}
}
and use it in the JSON parsing like this for example
boolean isfamily = convertIntToBool(jsonPhotoObject.getInt("isfamily"));
I guess you already know about the JSON parsing so I won't give so much example, but if you have another question about my answer feel free to ask in the comment :)
we assume the jsonString is your json result. You can get the your values like this:
protected String doInBackground(String... FlickrString) {
try {
JSONObject result = new JSONBOject(jsonString);
JSONObject photots = (JSONObject)result.get("photos");
JSONArray photosArray = (JSONArray) result.get("photo");
for(int i = 0; i < photosArray.length(); i++) {
JSONObject item = potosArray.get(i);
//ispublic
int ispublic = item.getInt("ispublic");
//isfriend
int isfriend = item.getInt("isfriend");
//isfamily
int isfamily = item.getInt("isfamily");
}
json = getValue();
return json.getString(FlickrString[0]);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
I would recommend that you try either Jackson or Gson and convert the JSON into some POJOs. I find that it's easier and less error prone to work with java objects instead of JSONObject, JSONArray and such. Here's an example of how it would work using Jackson. First we create the Objects that map to the JSON data:
public class Photos {
#JsonProperty
private int page;
#JsonProperty
private int pages;
...
#JsonProperty("photo")
public List<Photo> photoList;
}
public class Photo {
#JsonProperty
private String id;
#JsonProperty
private String owner;
...
#JsonProperty("ispublic")
public boolean isPublic;
#JsonProperty("isfriend")
public boolean isFriend;
#JsonProperty("isfamily")
public boolean isFamily;
}
Once we've created our pojos we can convert the JSON data into objects using the ObjectMapper. AT least when it comes to Jackson it automatically tries to convert integers to boolean (0 = false, anything else = true) and Strings to booleans ("true" and "false").
ObjectMapper mapper = new ObjectMapper();
Photos photos = mapper.readValue(json, Photos.class);
for(Photo photo : photos.photoList) {
if(photo.isPublic) {
// do something
}
}
PS I've made some of the properties of the pojos public to make the example shorter. You may wish to add getters and keep the properties private.
I am using a New Runnable httprequest data loading in one of my classes. I use that class to populate a ListView in one of my Activities, but the thing is that the views are loading before the data has been loaded.. I tried moving my initialize method, which initializes all views, but nothing happened. Every time I load the app, I have to reload the main view because there are no entries in the ListView. LoadReportList() is the method that makes an instance of the class holding the http request method.
public class HomeActivity extends Activity {
private ArrayList<Report> reportList = null;
ListView listview;
private final boolean DEBUG = true;
private MyCustomArrayAdapter adapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
}
#Override
protected void onResume()
{
super.onResume();
loadReportList();
initialize();
}
/**
* This method initializes all the components needed for the activity
*/
private void initialize()
{
/* Get a reference of the listview in our xml view */
listview = (ListView) findViewById(R.id.reportsList);
adapter = new MyCustomArrayAdapter(this, R.layout.single_listview_row);
try{
// Populate the list, through the adapter
for(final List_Item entry : getListEntries()) {
adapter.add(entry);
if(DEBUG)Log.i("HomeActivity","in adding List_Item entries to the adapter");
}
}catch(Exception e){
Log.i("In initialize() HomeActivity","Could not load the list with entries");
loadReportList();
}
listview.setAdapter(adapter);
listview.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
/* Class to assist us in loading the activity */
Class editClass = null;
try {
editClass = Class.forName(".DetailsActivity");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/* create bundle to pass the ID of the deck that was clicked */
Bundle reportPassed = new Bundle();
//reportPassed.putInt("Report", reportList.get(4).getId());
reportPassed.putSerializable("report", reportList.get(position));
/* Start the new intent and also pass a bundle that will contain the name of the card that was clicked */
Intent ourIntent = new Intent(HomeActivity.this, editClass);
ourIntent.putExtras(reportPassed);//passing the bundle to the activity
//start the activity
startActivity(ourIntent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
/* Create the list of objects of type List_Item, in our case it will be Decks */
private List<List_Item> getListEntries(){
/* Create an ArrayList of List_Items */
final ArrayList<List_Item> entries = new ArrayList<List_Item>();
if(reportList == null || reportList.isEmpty())
loadReportList();
/* Create the rows for the ListView by adding them into the ArrayList "entries".
* reportList is a global ArrayList<Report> that we populate by a method call to the class JsonParser.
* Look above.
* */
for(int i = 0; i < reportList.size(); i++) {
if(DEBUG)Log.i("getListEntries HomeActivity","Passing through reportlistEntries");
entries.add(
new List_Item(((Report)reportList.get(i)).getType(), Integer.toString(((Report)reportList.get(i)).getId()), ((Report)reportList.get(i)).getId())
);
}
return entries;
}
//This method loads the reportList arraylist with all Report objects
void loadReportList(){
try {
reportList = new JsonParser().getArrayList();
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
Here is my HTTP request:
//The constructor simply calls the getHttpResponse()
public JsonParser() throws UnsupportedEncodingException, IllegalStateException, IOException, JSONException
{
getHttpResponse();
}
/*
* This method returns an HttpResponse
*/
public void getHttpResponse(){
Log.i("getHttpResponse", "Right after declaring HttpResponse response");
new Thread(new Runnable() {
public void run() {
runRequest();
}
}).start();
}
void runRequest()
{
HttpResponse response = null;
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
try {
request.setURI(new URI("http://....../report_data.json"));
response = client.execute(request);
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(response!= null)
Log.i(response.toString(), "testing response.toString()");
//call to populate the list
try {
populateList(response);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Instead of using a java thread you can take advantage of the AsyncTask class of the Android SDK. You can show a progress dialog onPreExecute method, do all the heavy work(in your case the http stuff) in the doInBackground method and populate your list and dismiss the progress dialog in the onPostExecute method. You can create an inner class e.g Task which extends the AsyncTask method and call it from onCreate or onResume ,whatever suits you, like this.
new Task().execute();
AsyncTask has given the name"Painless threading" because it is there to make our life easier. It is consider good practice to reuse already implemented code which is intended for such tasks.
You can find many threads regarding AsyncTasks use in StackOverflow e.g progressDialog in AsyncTask
So what you need to do is call initialize() after your runRequest code completes.
I agree with the above poster that an AsyncTask will make this easy. Get rid of the threading code in your JsonParser class. AsyncTask will take care of that for you.
Here's a snippet.
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... voids) {
myparser = new JSONParser();
myparser.runRequest()
}
#Override
protected void onPostExecute(Void aVoid) {
initialize();
}
}.execute();
I'm trying to parse from an HTML page that only has a body and in the body is a pre tag but thats it. I need to get the info from it and put it in my android app that is using phonegap. I know javascript pretty well. I heard Jsoup will work well but I'm not sure how to output the data pulled using Jsoup as text that I can display.
Thank you for help in advance!
You could try like this.
try {
Document doc = Jsoup.connect(url).get();
Element element = doc.select("input[name=username]").first();
String get_value = element.attr("value");
Log.e(Tag, get_value);
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.e(Tag, e.toString());
}
if the html is like:
<........
...........>
<........>
<input name='username' value='fantastic' type='text' .... />
<........
...........>
<........>
the output will be fantastic
Edited
for your case:
new Thread( new Runnable() {
#Override
public void run() {
try {
Document doc = Jsoup.connect(url).get();
Element element = doc.select("body").first();
String get_value = element.text();
Log.e(Tag, get_value);
} catch (Exception e) {
// TODO Auto-generated catch block
Log.e(Tag, e.toString());
}
}
}).start();
N.B: i have not run this code. but u should try this.
how to use it:
public class MainActivity extends FacebookActivity {
private TextView textview;
private String get_value;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textview = (TextView)findViewById(R.id.your_textview_id);
new Thread( new Runnable() {
#Override
public void run() {
try {
// marked for your use
Document doc = Jsoup.connect(url).get();
Element element = doc.select("body").first();
get_value = element.text();
// marked for your use
textview.setText(get_value);
Log.e(Tag, get_value);
} catch (Exception e) {
// TODO Auto-generated catch block
Log.e(Tag, e.toString());
}
}
}).start();
// textview.setText(get_value);
}
}
Hi I am building an app which requires the user to press buttons (total 8 buttons). These buttons used to send strings to the server onclick . The problem here I'm having is when i press any of the button after connecting to the server it sends the string as it should but the 2nd time nothing happens. I was suggested to use doInBackground() from AsyncTask, to run keep running the socket and write to it each time the buttons are pressed. But i am unable to do so. What should I do ? I don't know where is the problem. Here I'm putting my code.
This is my Activity
public class Acontroller extends Activity {
Button bForward;
Button bBackward;
Button bRight;
Button bLeft;
Button bSelect;
Button bStart;
Button bB;
Button bA;
Socket s;
DataOutputStream os;
String ip;
// MyAppActivity ip = new MyAppActivity();
MyThread start = new MyThread();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.nesskin);
bForward = (Button) findViewById(R.id.bForward);
bBackward = (Button) findViewById(R.id.bBackward);
bRight = (Button) findViewById(R.id.bRight);
bLeft = (Button) findViewById(R.id.bLeft);
bSelect = (Button) findViewById(R.id.bSelect);
bStart = (Button) findViewById(R.id.bStart);
bA = (Button) findViewById(R.id.bA);
bB = (Button) findViewById(R.id.bB);
Bundle gotIP = getIntent().getExtras();
ip = gotIP.getString("ipAddress");
// start.doInBackground(ip);
//start.execute(ip);
// sock.start();
}
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
bForward.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
start.execute(ip);
}
});
And from the thread.
public class MyThread extends AsyncTask <String, Void, String>{
Socket s;
DataOutputStream os;
String ip;
String cmd;
#Override
protected void onPreExecute() {
Log.i("AsyncTask", "onPreExecute");
}
#Override
protected String doInBackground(String... params) {
int port = 2222;
// TODO Auto-generated method stub
if(s.isConnected()){
try {
os.writeUTF("forward");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
try {
s= new Socket(ip, port);
os = new DataOutputStream(s.getOutputStream());
os.writeUTF("forward");
}catch(Exception e){
e.printStackTrace();
}
finally{
if (s!= null){
try {
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (os != null){
try {
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
return null;
}
My objective is as many times the user clicks the buttons the respective strings must be send to the server. Here is my server code I'm using PC as server.
public class Server
public static void main(String[] args) throws AWTException {
String msg_received = null;
String fw = "forward";
String bw = "backward";
String l = "left";
String r = "right";
String se = "select";
String st = "start";
String a = "a";
String b = "b";
String fin = "finish";
// Boolean finish = (msg_received.equal(fin));
Robot robot = new Robot();
try {
ServerSocket ss = new ServerSocket(2222);
System.out.println("Server Started...");
while (true) {
Socket s = ss.accept();
System.out.println("Connection Request Received");
DataInputStream DIS = new DataInputStream(s.getInputStream());
msg_received = DIS.readUTF();
System.out.println(msg_received);
// s.close();
// ss.close();
if (msg_received.equals(fw)) {
// tu yeh kerna
robot.keyPress(KeyEvent.VK_UP);
robot.keyRelease(KeyEvent.VK_UP);
}
Please help me it really important to me. Thanks in advance.
You can't re-use an AsyncTask. You have to create a new object and call execute.
Replace
start.execute();
with
start = new MyThread();
start.execute(ip);
or if you can get away with removing the instance when it's done, then you can just do this:
(new MyThread()).start();
EDIT:
To send parameters to AsyncTask, do this:
start.execute(ip, cmd, param3, param4, param5);
in doInBackground collect the parameters like so:
protected Void doInBackground(String... params)
{
String ipParam = params[0];
String cmdParam = params[1];
String thirdParam = params[2];
String fourthParam = params[3];
String fifthParam = params[4];
}
You can pass as many Strings as you want into params and it will automatically create a new array containing all the parameters at runtime. Just note that if you only pass in two, then the params size will only be two. If you pass in 100 parameters, then params will be 100 units in size.