public String getBrotherHood() throws Exception{
client = new DefaultHttpClient();
get = new HttpGet(uri);
res = client.execute(get);
sl = res.getStatusLine();
sCode = sl.getStatusCode();
if(sCode==200)
{
try{
reader = new BufferedReader(new InputStreamReader(res.getEntity().getContent()));
readBuffer = new StringBuffer();
while((nl = reader.readLine())!=null){
readBuffer.append(nl);
}
reader.close();
}finally{
if(reader !=null)
{
try{
reader.close();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
}
return readBuffer.toString();
}
}
I have this code, is this the proper way of writing it, or should i need to follow any coding pattern or standards ??
Please give me some suggestions coz im not to Android Coding.
Update:
public class JSONData {
public ArrayList<String> getBrotherHoodJSON() throws JSONException,IOException,Exception{
ArrayList<String> item = new ArrayList<String>();
JSONArray jA = new JSONArray(getBrotherHood());
for(int i=0; i<jA.length(); i++)
{
JSONObject jO = jA.getJSONObject(i);
String n = jO.getString("name");
item.add(n);
Log.i("JsonData:",jO.getString("name"));
}
return item;
}
public String getBrotherHood() throws Exception{
BufferedReader in = null;
String data= null;
HttpClient client = new DefaultHttpClient();
URI uri = new URI("http://fahidmohammad.in/demo/Android/api.php?user=fah");
HttpGet get = new HttpGet();
get.setURI(uri);
HttpResponse res = client.execute(get);
StatusLine sl = res.getStatusLine();
int sCode = sl.getStatusCode();
if(sCode==200)
{
try{
in = new BufferedReader(new InputStreamReader(res.getEntity().getContent()));
StringBuffer sb = new StringBuffer();
String nl;
while((nl = in.readLine())!=null){
sb.append(nl);
}
in.close();
data = sb.toString();
Log.i("Raw Data:",data);
return data;
}finally{
if(in !=null)
{
try{
in.close();
return data;
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
}
return data;
}
Here is the updated version the same code.
Taken care of all the mentioned issues.
And also its working like a charm, but don't know the stability of it.
You obviously have declared all variables outside your method even though they seem to be used only within this method. That makes no sense. It prevents several objects from being garbage collected. You better move the declaration into the method.
And the declaration throws Exception doesn't make much sense either. You are better of if you either declare a specific exception that could likely occur or if you convert all unlikely exceptions into RuntimeException so you don't need to declare them.
There is a default code formatter is available eclipse. after wrote your code just type "Control + Shift + F". Your android code will formatting automatically.
one more important point regrading readBuffer varible
At the last of the function you are returning readBuffer.toString() and you initialized this only when status in 200. But if status in not 200 then it would be null (assuming as declaration is not visible ) so null.toString() will thought exception.
Related
I am having trouble reading object-data from a .txt-file using the readObject()-method from ObjectInputStream.
I am writing multiple User-objects to a .txt to save users when the server for the program is down, and the writing works fine, though when I am trying to read the information back, I don't know how to loop through/read the next line in the file.
public void readObjectFromFile() {
boolean cont = true;
User user;
try {
FileInputStream fileIn = new FileInputStream("files/userlist.txt");
ObjectInputStream objectIn = new ObjectInputStream(fileIn);
while(cont){
Object obj = objectIn.readObject();
if(obj != null) {
registeredUsers.add((User)objectIn.readObject());
user = (User)obj;
userPasswords.put(user.getUsername(), user.getPassword());
System.out.println(user.getUsername());
}else {
cont = false;
}
}
}catch (Exception ex) {
ex.printStackTrace();
}
}
public void addUserToDatabase(User user) {
try(FileOutputStream fos = new FileOutputStream("files/userlist.txt", true);
ObjectOutputStream oos = new ObjectOutputStream(fos)){
oos.writeObject(user);
oos.write('\n');
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
I would want to read the file line-by-line, and store the information of every line in a User-object and store it in the registeredUsers-list.
Okay I solved it!
public void readUsersFromFile() {
try {
FileInputStream fileIn = new FileInputStream("files/userlist.dat");
ObjectInputStream objectIn = new ObjectInputStream(fileIn);
boolean keepReading = true;
try {
while(keepReading) {
User user = (User)objectIn.readObject();
registeredUsers.add(user);
userPasswords.put(user.getUsername(), user.getPassword());
System.out.println(user.getUsername());
objectIn = new ObjectInputStream(fileIn);
}
}catch(EOFException e) {
keepReading = false;
}
}catch (Exception ex) {
ex.printStackTrace();
}
}
Problem: You are reading twice in while loop.
First Call:
objectIn.readObject()
Second Call:
registeredUsers.add((User)objectIn.readObject());
Solution:
Do not call readObject() method twice use the reference that is already been taken.
Other then functional problem, you can also correct the following things to make your code better:
Don't make while loop so complex.
No need to use separate boolean counter in while loop.
Just typecast once to user not multiple times (at the time of readObject() call itself).
Please refer following code:
User user = null;
while((user = (User) objectIn.readObject()) != null){
registeredUsers.add(user);
userPasswords.put(user.getUsername(), user.getPassword());
System.out.println(user.getUsername());
}
Are you already getting the data from the file?
I have done this before with pipe-delimited files ("|"), so:
value1|value2|value3
Not sure of the makeup of your file, but if you are already reading the data then you can skip to next lines & make new User objects like so:
private List <UserEntry> collectFileContents(InputStream is, String fileName) throws Exception {
try {
List <UserEntry> userEntries = new ArrayList <UserEntry>();
String line = "";
BufferedReader br = new BufferedReader(new InputStreamReader(is));
br.readLine();
while ((line = br.readLine()) != null) {
if (line.length() > 0) {
UserEntry entry = new UserEntry();
try {
String[] lineValues = line.split("\\|",-1);
entry.setVal1(lineValues[0]);
entry.setVal2(lineValues[1]);
//etc..
userEntries.add(entry);
} catch (ArrayIndexOutOfBoundsException ex) {
//error handling here
continue;
}
}
}
return userEntries;
}catch(Exception ex) {
//error handling here
}
}
This should create a list of Users, and I save them to the DB in a different method. But you can do it however you like. Also of note - in my file I have a title line as the first line. So this code will skip the first line. Again, not sure about how your file is set up.
Good evening, I'm sorry for my english. I want to try to deduce, using a link from json in the console. Sometimes is used json-simple-1.1.1.jar. I do not understand what the problem is, writes
Exception in thread "main" java.lang.NullPointerException at
kkkkkkkkkkkk.main.main (main.java:34)
private static final String filePath = "http://ksupulse.tk/get_all.php";
public static void main(String[] args) throws org.json.simple.parser.ParseException {
try {
URL serverAddress = new URL(filePath);
HttpURLConnection connection = (HttpURLConnection) serverAddress.openConnection();
connection.connect();
int rc = connection.getResponseCode();
if(rc == 200) {
String line = null;
BufferedReader reader = new BufferedReader(new java.io.InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
while((line = reader.readLine()) != null)
sb.append(line + '\n');
JSONObject obj = (JSONObject) JSONValue.parse(sb.toString());
//error
JSONArray array = (JSONArray) obj.get("response"); //<-------err this line
for(int i = 0; i < array.size(); i++) {
JSONObject list = (JSONObject) ((JSONObject)array.get(i)).get("list");
System.out.println(list.get("id")+": "+list.get("name"));
}
} else {
System.out.println("Connect error");
}
connection.disconnect();
} catch (java.net.MalformedURLException e) {
e.printStackTrace();
} catch (java.net.ProtocolException e) {
e.printStackTrace();
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
Can u provide the json text ?This is happening due to improper parsing of json text. The error is "Null Pointer Exception" . These types of error occur when you try to access some undefined resource . A good way to debug this one is to use a general exception and try to find the exact error . Your code is only handling 3 errors .You need to handle other errors also. Try using this.
try{
//Some code
}(Exception e){
System.out.println("Error:"+e.toString());
}
I'm working in my Twitch IRC Bot and we got a Problem.
We receive alot of information through the twitch API (json) like Who followed, dateOf .. viewercounts.. amount of followers and stuff like that.
Were making a Follow-Function to read all the names out of the whole list and set all into our database. First off we tried to just read all and system.output them but we always get the error: org.json.JSONException: JSONArray[100] not found.
We noticed that "0" is holding an array as well so we set the loop to 0-99 and it should change the link then by adding 100+ (next site) and read the JSON again. then it should just continue the loop with the next site.
Below is the Main code as well for the read-methods.
We tried debugging but we wasn't able to find a solution yet x(
MyBot Main Code Snippet:
JSONObject follower = null;
String followername = null;
int listnumber;
offsetvalue = 0;
for(int i = 0; i < TwitchStatus.totalfollows; i++) {
try {
follower = TwitchStatus.followerarray.getJSONObject(i);
} catch (JSONException e2) {
e2.printStackTrace();
}
try {
followername = follower.getJSONObject("user").getString("display_name");
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("array ist: "+i +" " +followername);
listnumber = offsetvalue+99; // 0+99
if (i == listnumber){
offsetvalue = offsetvalue+100;
try {
TwitchStatus.FollowerTicker();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
// System.out.println("Follower abgleichs-Liste: "+followername);
}
And there is the Reader Method:
////////////////////////////////////////////////////////////////////////////////////
// Twitch Follower Ticker
////////////////////////////////////////////////////////////////////////////////////
private String readAll4(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public JSONObject readJsonFromUrl4(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll4(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
public static void FollowerTicker() throws IOException, JSONException {
json = readJsonFromUrl2("https://api.twitch.tv/kraken/channels/dotastarladder_en/follows?direction=DESC&limit=100&offset="+MyBot.offsetvalue+"");
followerarray = json.getJSONArray("follows");
{
JSONObject follower = followerarray.getJSONObject(0);
neuerfollower = follower.getString("created_at");
fname = follower.getJSONObject("user").getString("display_name");
totalfollows = json.getInt("_total");
}
}
Note from the API docs:
limit optional integer Maximum number of objects in array. Default is 25. Maximum is 100.
So, what do you do? Query the next one, of course! Here's the bit of JSON from the linked page, and an example next URL. Basically, you just put an offset in, but the URL already declares it, so...
{
"_total": 1234,
"_links": {
"next": "https://api.twitch.tv/kraken/channels/test_user1/follows?direction=DESC&limit=25&offset=25",
How I would solve this problem is something like this:
Create an AsyncTask that takes in the URL to parse the JSON text.
When the data has been received, start a new task to read the next one.
Read everything received in this JSON string
Compile everything after it has been downloaded as needed.
I have a function which fetches a certain website's HTML code. Eventually that function will return the whole page as an array. I am trying to save the page in another array, but it will always throw an exception (ArrayIndexOutOfBoundsException) for some reason.
I am not sure if I am just missing something elementary or if it's more than just that. To give you some of my code:
protected String[] doInBackground(String... login)
{
String[] page = new String[1024];
try {
page = executeHttpGet(); //THIS IS WHERE IT FAILS
} catch (Exception e) {
page[0] = "Error";
}
return page;
}
public String[] executeHttpGet() throws Exception {
URL u;
InputStream is = null;
DataInputStream dis;
String s;
int i = 0;
String[] page = new String[1024];
addSecurityException();
Authenticator.setDefault(new MyAuthenticator(activity));
try {
u = new URL("https://myurl.com");
is = u.openStream();
dis = new DataInputStream(new BufferedInputStream(is));
while ((s = dis.readLine()) != null) {
if (s.toString().length() > 10)
{
page[i] = s.toString();
i++;
}
}
} catch (IOException ioe) {
}
finally {
try {
is.close();
} catch (IOException ioe) {
}
}
return page;
}
}
Does anyone have any ideas why I am not able to assign the returned array to the array in doInBackground()? Help would be greatly appreciated.
Your catch-blocks are empty, which is a terrible idea, because you'll get no information when something goes wrong.
You don't need to initialize page on its declaraton, when you re-assign it two lines below (you'll have to change the catch-block to create a new array, 'though).
Have you checked that your URL doesn't return more than 1024 lines?
You don't need s.toString() when s is a String, because it will just return s.
When analyzing an exception, you should look at the whole stacktrace to find out where exactly the problem occurs.
When asking about an exception you should post the whole stacktrace!
When you have an unspecified number of elements List is a more flexible and easier-to-use alternative to arrays. Generally speaking, arrays are quite low-level and there's barely a reason to use them directly (they are very useful for building List implementations).
For a few weeks I have been developing a email client for android, I have been ignoring parsing email content for a while as I have never been able to get it to work. Thus, the time has come to ask for help!
I have been looking around and I have come across a few methods I have tried but never had much success with! Currently my closest attempt would have to be:
private String parseContent(Message m) throws Exception
{
//Multipart mp = (Multipart)c;
//int j = mp.getCount();
/*for (int i = 0; i < mp.getCount(); i++)
{
Part part = mp.getBodyPart(i);
System.out.println(((MimeMessage)m).getContent());
content = content + part.toString();
//System.out.println((String)part.getContent());
}*/
Object content = m.getContent();
String contentReturn = null;
if (content instanceof String)
{
contentReturn = (String) content;
}
else if (content instanceof Multipart)
{
Multipart multipart = (Multipart) content;
BodyPart part = multipart.getBodyPart(0);
part.toString();
contentReturn = part.getContent().toString();
}
return contentReturn;
}
But it does not work and I get gibberish such as "javax.mail.internet.MimeMultipart#44f12450".
Can anyone see where I am going wrong?
Thanks,
Rhys
None of the above suggestions is valid. You don't need to do anything complex here. Mimemessage has got message.writeTo(outputStream);
All you need to print the message is:
message.writeTo(System.out);
The above code will print the actual mime message to the console (or you can use any logger).
Save the content to .eml and you can open it in outlook. Simple as that!
Multipart multipart = (Multipart) content;
BodyPart part = multipart.getBodyPart(0);
part.toString();
contentReturn = part.getContent().toString();
When you have BodyPart part, you should keep testing
if(part.getContent() instanceof String){
...
}
I had the same issues while parsing Message of javax mail. In my workaround i found a weird thing. Listing mail from POP3 was not giving me Mail body content. So used IMAP which worked for me. Now i'm able to parse Text/plain as well as Text/Html and read the body. To parse the same i used following method.
public String printMessage(Message message) {
String myMail = "";
try {
// Get the header information
String from = ((InternetAddress) message.getFrom()[0])
.getPersonal();
if (from == null)
from = ((InternetAddress) message.getFrom()[0]).getAddress();
System.out.println("FROM: " + from);
String subject = message.getSubject();
System.out.println("SUBJECT: " + subject);
// -- Get the message part (i.e. the message itself) --
Part messagePart = message;
Object content = messagePart.getContent();
// -- or its first body part if it is a multipart message --
if (content instanceof Multipart) {
messagePart = ((Multipart) content).getBodyPart(0);
System.out.println("[ Multipart Message ]");
}
// -- Get the content type --
String contentType = messagePart.getContentType();
// -- If the content is plain text, we can print it --
System.out.println("CONTENT:" + contentType);
if (contentType.startsWith("TEXT/PLAIN")
|| contentType.startsWith("TEXT/HTML")) {
InputStream is = messagePart.getInputStream();
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
String thisLine = reader.readLine();
while (thisLine != null) {
System.out.println(thisLine);
myMail = myMail + thisLine;
thisLine = reader.readLine();
}
}
System.out.println("-----------------------------");
} catch (Exception ex) {
ex.printStackTrace();
}
return myMail;
}
Hope it helps someone.
I also got the same error any tried almost every thing, but the solution worked for me is
private String getFinalContent(Part p) throws MessagingException,
IOException {
String finalContents = "";
if (p.getContent() instanceof String) {
finalContents = (String) p.getContent();
} else {
Multipart mp = (Multipart) p.getContent();
if (mp.getCount() > 0) {
Part bp = mp.getBodyPart(0);
try {
finalContents = dumpPart(bp);
} catch (Exception e) {
e.printStackTrace();
}
}
}
return finalContents.trim();
}
private String dumpPart(Part p) throws Exception {
InputStream is = p.getInputStream();
// If "is" is not already buffered, wrap a BufferedInputStream
// around it.
if (!(is instanceof BufferedInputStream)) {
is = new BufferedInputStream(is);
}
return getStringFromInputStream(is);
}
private String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
Hope this will help someone.
Not entirely sure, but what it sounds like is you want to convert a MimeMessage into a String. Strictly speaking, there is no "standard" translation for MimeMessage to String, but here is a chunk of code that I wrote a couple of years back that attempts to generate one such translation. Only tested on English messages, so i18n will have to be something you think about yourself.
Unfortunately SO's stupid filter seems to think that my code sample is an image and won't let me post it: take a look at the class at http://pastebin.com/pi9u5Egq : the code is doing a bunch of otherwise unnecessary things (it was spitting it out into HTML that was rendered using flying saucer), and also requires Jakarta Commons Lang, javamail and activation libraries, but it works for me. You would invoke it like this:
fetchText(message, null, false, false);
To get a text string. Try that out for size.