I'm new to Android development and i am trying to make a custom class which I can access in my activities to read text from files on a server. i have a custom function which works fine but i need to access this function in many activities so i need a custom class which performs the same action. My function is here
public String GetLinkss(String url) {
String StringBuffer="";
String stringText="";
try {
URL link = new URL(url);
BufferedReader bufferReader = new BufferedReader(
new InputStreamReader(link.openStream()));
while ((StringBuffer = bufferReader.readLine()) != null) {
stringText += StringBuffer;
}
bufferReader.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return stringText;
}
Create a package like this:
package com.whatever.utils;
public class Utils {
private Context mContext;
// constructor
public Utils(Context activityContext) {
mContext = activityContext;
}
public static String GetLinkss(String url) {
// your stuff
}
// other functions/methods used throughout the application
}
And then you use it like this wherever you want:
String myStringText = Utils.GetLinkss("my_url");
HTH
Related
I am creating an application that makes calls to the Hitbox API. I am trying to get the game name (listed as category_name from a list.
Thus far, I have managed to get the game name one time during the programs running stage, however when I change where to get the game name from, the program doesn't do anything. I am at a loss as to what could cause it not to send another request to the server.
public void apiConnect(){
String channel = text.getText();
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://api.hitbox.tv/media/live/" + channel);
HttpResponse response = null;
try {
response = client.execute(request);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// Get the response
BufferedReader rd = null;
try {
rd = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
} catch (UnsupportedOperationException | IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String line = "";
try {
while ((line = rd.readLine()) != null) {
hitbox.append(line);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
FileUtils.writeStringToFile(new File("hitbox.json"), hitbox.getText());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String game = null;
FileInputStream fileHitbox = null;
try {
fileHitbox = new FileInputStream(new File("hitbox.json"));
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
String strHitbox = null;
try {
strHitbox = IOUtils.toString(fileHitbox, "UTF-8");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
JSONObject obj = new JSONObject(strHitbox);
JSONArray ar = obj.getJSONArray("livestream");
for (int i = 0; i < ar.length(); i++)
{
game = ar.getJSONObject(i).getString("category_name");
nameOf.setText("Game Name: " + game);
}
File hb = new File("hitbox.json");
if(hb.exists()){
hb.delete();
}
}
The above sample is the defined function, and the Get Game Name button code is below:
btnGetGameName.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
apiConnect();
}
});
Could anyone suggest what is causing it to not work after the first request, and if possible suggest a solution?
EDIT: I have found the issue. The reading of the data from the API is appended to the hitbox variable. I have thus added a snippet that clears what "hitbox" variable has when the button is pressed, thus meaning the code works without issues.
Try to consume your response after your read it to release the resource :
rd = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
response.getEntity().consumeContent();
//Or if you have EntityUtils
EntityUtils.consume(response.getEntity());
source
My program is supposed to search for a computer name and update the computer name value in the same instance of the GUI that it was searched in. If I launch the application and search for the computer name and hit search, it won't appear in the same instance. If I hit run again, the computer name I just searched for appears in the label in the new instance of the GUI.
So basically at the moment I have to launch a new instance of the GUI to see the updated computer name. Any help is appreciated. I've been stuck on this for a long time now.
Relevant Code:
try (BufferedReader br = new BufferedReader(new FileReader("resultofbatch.txt")))
{
final Pattern PATTERN = Pattern.compile("CN=([^,]+).*");
try {
while ((sCurrentLine = br.readLine()) != null) {
String[] tokens = PATTERN.split(","); //This will return you a array, containing the string array splitted by what you write inside it.
//should be in your case the split, since they are seperated by ","
// System.out.println(sCurrentLine);
CN = sCurrentLine.split("CN=",-1)[1].split(",",-1)[0];
System.out.println(CN);
testLabel.setText(CN);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MISControlPanel window = new MISControlPanel();
window.frame.setVisible(true);
//testLabel.setText(CN);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
You can view the full class here: http://pastebin.com/8hH1TMD3
I am trying to access the
public static List<ChatThread> Chat_list of my ChatThread Class
from the run() method of my Client Class but i keep getting an empty array(Infact it throws an exception at that point : Exception in thread "Thread-2" java.lang.NullPointerException)
and am very certain that that arrayList exists and is not empty(Because i did a test on the arrayList in my ChatThread Class). Just take a look at my code.
Please I need your help on what to do.
Thanks.
This is the class containing the arrayList :
public class ChatThread extends Thread {
private Socket sc;
private String cherry_name;
private String passwd;
public static List<ChatThread> Chat_list = new ArrayList<ChatThread>(); //THE STATIC ARRAY LIST
private BufferedReader br;
private BufferedWriter bw;
public ChatThread(Socket sc){
try {
this.sc=sc;
System.out.println(sc);
br = new BufferedReader(new InputStreamReader(sc.getInputStream()));
bw = new BufferedWriter(new OutputStreamWriter(sc.getOutputStream()));
String help = br.readLine();
this.cherry_name=help.split("#")[0];
this.passwd=help.split("#")[1];
System.out.println(this.cherry_name);
System.out.println(this.passwd);
Chat_list.add(this); //This is where i add it to the arrayList
if(Chat_list.isEmpty()) //This is where i did the test
System.out.println("I am empty");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run(){
//Comparaison of information with that in the database
try{
bw.write("success");
bw.newLine();
bw.flush();
while(true){
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Socket getSc() {
return sc;
}
public String getCherry_name() {
return cherry_name;
}
}
As for the Client class :
public class Client extends Thread {
private Socket socket;
private BufferedReader br;
private BufferedWriter bw;
private ChatThread th;
private String cherry_name;
public Client(String cherry_name,String passwd){
try
{
socket = new Socket("127.0.0.1", 8888);
this.cherry_name=cherry_name;
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
bw.write(cherry_name+"#"+passwd);
bw.newLine();
bw.flush();
}
catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Erreur lors de la lecture du socket");
e.printStackTrace();
}
}
#SuppressWarnings("deprecation")
public void run()
{
try {
String help = br.readLine();
if(help.equals("failed")){
this.notify();
this.destroy();
socket.close();
}
else{
if(ChatThread.Chat_list.isEmpty()) System.out.println("Empty array!!!"); //This is where it says the array is empty whereas it wasn't the case in the ChatThread Class
for(ChatThread ct : ChatThread.Chat_list){
if(cherry_name.equals(ct.getCherry_name())){
th=ct;
break;
}
}
while(true){
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Error whilst reading from the socket");
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("Interruption");
e.printStackTrace();
}
}
public Socket getSocket() {
return socket;
}
}
And my server class :
public class Server {
public static void main(String[] args) {
try {
ServerSocket server =new ServerSocket(8888);
Socket sc;
System.out.println("Server Started");
while(true){
sc=server.accept();
System.out.println("New Connection");
new ChatThread(sc).start();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
A main class to instantiate the Client class :
public class help {
public static void main(String[] argv) {
new Client("Jerry","Smith").start();
}
}
Every access to a mutable object shared between two threads must be accessed in a synchronized way. Not synchronizing will lead to visibility and coherence issues like you're seeing.
You should not expose an ArrayList like that (even without multiple threads, public static mutable objects are already a very bad practice). Instead, you should encapsulate it in your own object, and make sure every access is synchronized properly.
It's hard to give a more concrete advice without seeing any line of your code.
I'm still struggling to find an answer to my question. I want to download 3 strings for each item in the listview to the phone. I know how to get all the data from the server, just not how to append the data to the litview, I'm really annoyed and this problem is dragging me down.
My Code:
public class ChatService extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chatservice);
try {
ContactsandIm();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
CheckLogin();
private void CheckLogin() {
// TODO Auto-generated method stub
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
/* login.php returns true if username and password is equal to saranga */
HttpPost httppost = new HttpPost("http://gta5news.com/login.php");
try {
// Execute HTTP Post Request
Log.w("HttpPost", "Execute HTTP Post Request");
HttpResponse response = httpclient.execute(httppost);
String str = inputStreamToString(response.getEntity().getContent())
.toString();
Log.w("HttpPost", str);
if (str.toString().equalsIgnoreCase("true")) {
Log.w("HttpPost", "TRUE");
try {Thread.sleep(250);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//put intent here(21/3/12);
} else {
Log.w("HttpPost", "FALSE");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private StringBuilder inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Return full string
return total;
}
private void ContactsandIm() throws URISyntaxException, ClientProtocolException, IOException {
// TODO Auto-generated method stub
BufferedReader in = null;
String data = null;
HttpClient get = new DefaultHttpClient();
URI website = new URI("http://www.gta5news.com/test.php");
HttpGet webget = new HttpGet();
webget.setURI(website);
HttpResponse response = get.execute(webget);
Log.w("HttpPost", "Execute HTTP Post Request");
in = new BufferedReader (new InputStreamReader(response.getEntity().getContent()));
//now we'll return the data that the PHP set from the MySQL Database.
if (in.equals("True")); {
Toast.makeText(this,"yay", Toast.LENGTH_LONG).show();
}
}
// end bracket for "ContactsandIm"
private void showToast(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
}
Use an ArrayAdapter on your list, and add items to this adapter, then call notifyDatasetChanged on it, and zou
First of all when we connect to Server using the Network Threads, then you should go for AsyncTask or Handlers. Which is specially used for handling such Threads.
ListView can be created by using default Listview ans also the Custom Listview where we can design our own Row design in the Row.xml and the same design will be used for all the rows.
If you want move forward or go for some advanced Listview then even we can use 'n' number of designs for different rows.
Here in your case, You should use a AsyncTask for fetching the data and use the Listview for displaying rows.
You can get more information from the below link.
https://docs.google.com/leaf?id=0B2qCFbmeiTFxN2ViZjVlOTUtNmY3ZS00NThhLTg3N2UtYjVkYjgyM2Y4MWUy&hl=en&authkey=COeP8JYN
I'm looking for a place where are objects after serialization ? I would like to put serialized objects(created in another app) to my android project and then only load this files in my game. The problem is that I don't know where do I have to put this objects ? and even if I save object from android app it never saves in my project folder. My load and save functions for objects
public static void save(Context context, Map obj, String nazwa)
{
FileOutputStream str = null;
ObjectOutputStream objStr = null;
try {
str = context.openFileOutput(nazwa, Context.MODE_PRIVATE);
objStr = new ObjectOutputStream(str);
objStr.writeObject(obj);
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
} finally
{
try
{
if (objStr != null) objStr.close();
} catch (IOException e) {}
try
{
if (str != null) str.close();
} catch (IOException e) {}
}
}
public static Map load(Context context, String nameFile)
{
Map obj = null;
FileInputStream str_w = null;
ObjectInputStream obj_w = null;
try
{
str_w = context.openFileInput(nameFile);
obj_w = new ObjectInputStream(str_w);
obj = (Map) obj_w.readObject();
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
} catch (ClassNotFoundException e)
{
e.printStackTrace();
} finally
{
try
{
if (obj_w != null) obj_w.close();
} catch (IOException e) {}
try
{
if (str_w != null) str_w.close();
} catch (IOException e) {}
}
return obj;
}
If I copy my object file to /levels/ and use
final Map map2 = MapManager.load(this, "/levels/map1.lvl");
or
final Map map2 = MapManager.load(this, "levels/map1.lvl");
it never works
How should I do it ?
You're storing them as app private files (Context.MODE_PRIVATE) to a folder only the app has access to, so no other application will be able to access them.
I think the easiest way to store them so they can be shared between apps is to store them to the sdcard using:
Environment.getExternalStorageDir();
Be aware to store them as globally readable.