OpenWeatherMap API : Encounter NullPointerException [duplicate] - java

This question already has answers here:
Android 8: Cleartext HTTP traffic not permitted
(37 answers)
Closed 2 years ago.
I'm building an application on Android Studio that retrieves weather information in real time thanks to OpenWeatherMap and the API they offer.
The problem is, I'm using two phones with different SDKs. One is SDK 23 / Android 6.0 and the other is SDK 28 / Android 9.0.
Currently on the phone with SDK 23 I have no problem. However on the phone with SDK 28 I have a NullPointerException error. My second activity allows me to display information for city X and its weather information. So, finally the error I'm encountering on the phone with SDK 28 is this one :
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
I've looked into a lot of things to see where that could have come from, if it wasn't my AsyncTask or whatever, but I really don't see it.
Knowing that on the phone with the oldest version of Android it retrieves well the information from my editText that on the most recent version it doesn't retrieve it at all and the nullpointerException must come from there.
Do you know where this might be coming from?
Here is my AsyncTask :
public class ExecuteTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... strings) {
HttpURLConnection con = null ;
InputStream is = null;
try {
con = (HttpURLConnection) ( new URL(strings[0])).openConnection();
con.setRequestMethod("GET");
con.setDoInput(true);
con.setDoOutput(true);
con.connect();
// Let's read the response
StringBuffer buffer = new StringBuffer();
is = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
while ( (line = br.readLine()) != null )
buffer.append(line + "\r\n");
is.close();
con.disconnect();
return buffer.toString();
}
catch(Throwable t) {
t.printStackTrace();
}
finally {
try { is.close(); } catch(Throwable t) {}
try { con.disconnect(); } catch(Throwable t) {}
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
String message = "";
String degre="";
String idMeteo="";
JSONObject jsonObject = new JSONObject(s);
String infoWeatherToday = jsonObject.getString("weather");
JSONObject WeatherTemperature = jsonObject.getJSONObject("main");
Integer deg = WeatherTemperature.getInt("temp");
deg = deg - 273;
JSONArray array = new JSONArray(infoWeatherToday);
int tablongueur=array.length();
for (int i = 0; i < tablongueur; i++) {
JSONObject jsonSecondary = array.getJSONObject(i);
String main = "";
//Integer id;
main = jsonSecondary.getString("main");
// id = jsonSecondary.getInt("id");
switch (main) {
case "Clouds":
main = "Nuageux";
PhotoMeteo.setImageResource(R.drawable.cloud);
break;
case "Clear":
main = "Ensoleillé";
PhotoMeteo.setImageResource(R.drawable.sun);
break;
case "Rain":
main = "Pluie";
PhotoMeteo.setImageResource(R.drawable.rain);
break;
case "Snow":
main = "Neige";
PhotoMeteo.setImageResource(R.drawable.snow);
break;
case "Smoke":
main = "Brouillard";
PhotoMeteo.setImageResource(R.drawable.smoke);
break;
case "Drizzle":
main = "Brumeux";
PhotoMeteo.setImageResource(R.drawable.drizzle);
break;
default:
main = "Météo introuvable !";
PhotoMeteo.setImageResource(R.drawable.ic_warning);
}
if (main != "" /*&& id != null*/) {
message += main + "\r\n";
degre += deg + "°C";
//idMeteo += "L'id de la météo est" + id;
}
}
if (message != "") {
resultWeather.setText(message);
resultDegre.setText(degre);
//resultIdMeteo.setText(idMeteo);
} else {
Toast.makeText(AccueilActivity.this, "Une erreur a eu lieu ", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
And here is the intent that I keep from my first activity called RegisterActivity to give it as a parameter for the "name" of the city
Intent intent = new Intent(RegisterActivity.this, AccueilActivity.class);
intent.putExtra(EXTRA_TEXT,cityField.getText().toString());
startActivity(intent);
In my 2nd activity called "AccueilActivity"
Intent intent = getIntent();
if(intent!=null)
{
textViewVille.setText(intent.getStringExtra(EXTRA_TEXT));
ville = intent.getStringExtra(EXTRA_TEXT);
FindWeather();
}
And my final function called FindWeather which execute the AsyncTask
public void FindWeather() {
cityToFind = ville;
try {
ExecuteTask tasky = new ExecuteTask();
tasky.execute("http://api.openweathermap.org/data/2.5/weather?q=" + cityToFind + "&APPID={MYAPKKEY}&LANG=fr&UNITS=metric");
} catch (Exception e) {
e.printStackTrace();
}
}
Just I don't give you the value of my APK Key because it isn't something interesting but the value is present in the initial code.
If I have a last things to add, ville is a simple TextView and cityToFind the value of my editText on the first activity.
If you need anything of my source code I can give you more.
Thank you.

doInBackground is going to return null if there is any exception in your HTTP code.
That is passed to onPostExecute as the parameter.
You then try to constuct a JSONObject(null), which is an invalid argument
All in all, please pick a higher level HTTP library with fault tolerance built in
Comparison of Android networking libraries: OkHTTP, Retrofit, and Volley
I also suggest writing unit tests outside of that class and running them from the IDE rather than a device, so you verify the network calls actually work.

Related

Java Stack becomes empty for some reason

I'm working on an Android app that is going to call the DarkSky weather API (I have redacted my API key here for obvious reasons). My problem comes when I parse the JSON data and push it to a stack I named dataStack. At the time of pushing the stack I log its size and it shows correctly. However when my code reaches the buildGraph() method, the stack is now empty and all my data has disappeared. What causes the stack to empty?
EDIT: As of 30 minutes after posting I found a workaround. I am now returning the String and parsing it in my MainActivity Android class. However, I still do not know why the stack was being deleted. I would love to know :)
public class MainActivity extends AppCompatActivity {
Button button;
TextView progressLabel;
GraphView graph;
JSONObject jsonObject;
static Stack<DataPoint> dataStack = new Stack<>(); // stack for graph data points
static final String API_URL = "https://api.darksky.net/forecast/API_KEY/42.3611,-71.0570,"; // #TODO: delete API key before comitting to GitHub
static final String URL_TAIL = "?exclude=currently,flags,hourly"; // end of URL
static final long currTime = System.currentTimeMillis() / 1000L; // current UNIX time
static long unixTime = currTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
progressLabel = findViewById(R.id.progressLabel);
graph = findViewById(R.id.graph);
}
public void loadResults(View view) {
for (int x = 0; x < 2; x++) { // 7 API calls for each of 7 days
new APICall().execute();
unixTime -= 86400; // subtract 24 hours in UNIX time
dataStack.size();
}
buildGraph(); // after all data is gathered, build a graph using it
}
private void buildGraph() {
// #TODO: Method to build graph
Log.i("STACK pop", String.valueOf(dataStack.size()));
}
class APICall extends AsyncTask<Void, Void, String> { // Extend AsyncTask so we don't hijack the main UI thread
protected void onPreExecute() {
// Do stuff before executing the AsyncTask
progressLabel.setText("Fetching Data");
}
protected String doInBackground(Void... urls) {
// Execute background task here
try {
final String FULL_URL = API_URL + unixTime + URL_TAIL; // build the full URL with latest time
URL url = new URL(FULL_URL); // URL for the API call
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); // connection to URL
try {
// tools for reading API results
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
// accumulate results
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close(); // always close buffered reader
return stringBuilder.toString(); // return results
}
finally {
// inside a finally block so that no matter what we always end a connection that has been started
urlConnection.disconnect(); // end the connection
}
}
catch(Exception ex) {
Log.e("ERROR", ex.getMessage(), ex);
return null;
}
}
protected void onPostExecute(String response) {
// Do stuff after we're finished executing
if (response == null) {
response = "AN ERROR HAS OCCURRED";
}
else {
try {
jsonObject = new JSONObject(response); // create object from our response
JSONArray arr = jsonObject.getJSONObject("daily").getJSONArray("data"); // get data Array
String arrString = arr.getString(0); // full String
String[] splitString = arrString.split(","); // split String into array by comma
String time = splitString[0].substring(8); // time is the first index of the array, use substring to cutout unecessary info
String temp = splitString[11].substring(18);
dataStack.push(new DataPoint(Integer.valueOf(time), Float.valueOf(temp))); // push our data onto the stack as a DataPoint
Log.i("STACK push", String.valueOf(dataStack.toString()));
response = "Data received"; // display this to user
}
catch(Exception ex) {
response = "ERROR DURING JSON PARSING";
}
}
progressLabel.setText(response);
// parse data here
Log.i("INFO", response);
}
}
}
The stack is empty because result isn't in yet. The issue is with your loadResults().
public void loadResults(View view) {
for (int x = 0; x < 2; x++) { // 7 API calls for each of 7 days
new APICall().execute();
unixTime -= 86400; // subtract 24 hours in UNIX time
dataStack.size();
}
buildGraph(); // after all data is gathered, build a graph using it
}
You issued the new APICall().execute(); to request data and update the dataStack and you expect to get the dataStack results 'immediately' inside the same function loadResults()? It's not possible.
One solution is to remove the buildGraph() in loadResults() to inside onPostExecute().

Asynctask doesnt work after too many rows retrieved

I am doing an app where I synchronize my online DB to the offline DB everytime the user logs in. The table is dropped in offline, recreated then new rows gets added ( Its neccessary to drop it and add new instead of just checking and adding the rows that are not in the table already). I had about 200 rows in my online table and they are synchronised to my offline table relatively fast (in the background, then I tried 3000 and it was still processing. But When I generated 90 000 rows and tried to synchronize it to my offline DB it wouldnt move.
The log in onPreExecute() executed, but none of the logs in my doInBackground. json is not null.
For each retrieved row I am adding a row in offline.
Anyone know what could be the issue?
I tried adding LIMIT 200 in my PHP Scripts and still didnt do it, which was weird, cause when I had 200 rows it executed, but when I limit the output to 200 it does not.
Thank you for any answers, that would bring me closer to the solution.
public class SyncVykresToOffline {
String DataParseUrl = "/scriptsforandroidapplicationofflinemode/SyncVykresToOffline.php";
JSONObject json = null;
String str = "";
HttpResponse response;
DBHelper dbh;
private Context mContext;
public static boolean syncedvykres = false;
int k = 200;
public SyncVykresToOffline(Context context) {
mContext = context;
dbh = new DBHelper(mContext);
}
public class SyncVykres extends AsyncTask<Void, Void, Void>
{
public Context context;
public SyncVykres(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
Log.i("Poradie_zacal","ano");
}
#Override
protected Void doInBackground(Void... arg0)
{
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost(DataParseUrl);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("limit", String.valueOf(k)));
try {
myConnection.setEntity(new UrlEncodedFormEntity(nameValuePairs));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
try {
HttpResponse response = myClient.execute(myConnection);
} catch (IOException e1) {
e1.printStackTrace();
}
try {
response = myClient.execute(myConnection);
str = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
int i = 0;
try{
int vykres_version;
JSONArray jArray = new JSONArray(str);
json = jArray.getJSONObject(i);
Log.i("Poradie_json",String.valueOf(jArray.length()));
String
Nazov_vykresu;
int Version,
ID_vykres,
ID_stav,
ID_zakazka,
Poradie;
if(json == null) {
Log.i("Poradie","son is null");
}
while(json != null) {
Log.i("Poradie","been here");
ID_vykres = Integer.parseInt(json.getString("ID_vykres"));
vykres_version = dbh.getVykresVersion(ID_vykres);
Nazov_vykresu = json.getString("Nazov_vykresu");
ID_stav = Integer.parseInt(json.getString("ID_stav"));
ID_zakazka = Integer.parseInt(json.getString("ID_zakazka"));
Version = Integer.parseInt(json.getString("Version"));
Poradie = Integer.parseInt(json.getString("Poradie"));
Log.i("Poradie",json.getString("Poradie"));
dbh.SyncVykresToOffline(new technicky_vykres(ID_vykres,Nazov_vykresu,ID_stav,ID_zakazka,Version,Poradie));
i++;
json = jArray.getJSONObject(i);
}
} catch ( JSONException e) {
e.printStackTrace();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result)
{
syncedvykres = true;
}
}
}
Edit: added Logcat logs.
06-25 20:36:07.013 8278-8308/com.example.chris.normitapplication W/System.err: at org.json.JSON.typeMismatch(JSON.java:111)
at org.json.JSONArray.<init>(JSONArray.java:96)
at org.json.JSONArray.<init>(JSONArray.java:108)
at com.example.chris.normitapplication.offline.SyncVykresToOffline$SyncVykres.doInBackground(SyncVykresToOffline.java:102)
at com.example.chris.normitapplication.offline.SyncVykresToOffline$SyncVykres.doInBackground(SyncVykresToOffline.java:44)
at android.os.AsyncTask$2.call(AsyncTask.java:292)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
Edit 2: added PHP Script from where the JSON array is retrieved from:
<?php
include 'DatabaseConfig.php';
$conn = mysqli_connect($HostName,$HostUser,$HostPass,$DatabaseName);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
mysqli_set_charset($conn,"utf8");
$vykres = array();
$sql = "SELECT * FROM `technicky_vykres`";
$result = mysqli_query($conn, $sql) or die("Error in Selecting " . mysqli_error($conn));
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode($emparray);
$conn->close();
?>
Issue identified when logging STR:
<html>
<head><title>502 Bad Gateway</title></head>
<body bgcolor="white">
<center><h1>502 Bad Gateway</h1></center>
<hr><center>openresty</center>
</body>
</html>
My hunch is, its the data that is breaking the loop and causing your program to end without going through the complete data set. I just added simple try/catch (see below) to printout any data objects, that we can't parse and but still continue to process the next row. Of course you'll need to have better error handling in place for production quality code.
while(json != null) {
try{
Log.i("Poradie","been here");
ID_vykres = Integer.parseInt(json.getString("ID_vykres"));
vykres_version = dbh.getVykresVersion(ID_vykres);
Nazov_vykresu = json.getString("Nazov_vykresu");
ID_stav = Integer.parseInt(json.getString("ID_stav"));
ID_zakazka = Integer.parseInt(json.getString("ID_zakazka"));
Version = Integer.parseInt(json.getString("Version"));
Poradie = Integer.parseInt(json.getString("Poradie"));
Log.i("Poradie",json.getString("Poradie"));
dbh.SyncVykresToOffline(new technicky_vykres(ID_vykres,Nazov_vykresu,ID_stav,ID_zakazka,Version,Poradie));
i++;
json = jArray.getJSONObject(i);
}catch(Exception e){
//Something wrong with the data? log it and see if you can find the culprit row/data....
Log.i("The faulty jason obj: " + json);
continue; //Move on the next one....
}
}
The error indicates that JSONArray believes your response is not formed as a Json Array.
Here's the code within JSONArray throwing your error:
public JSONArray(JSONTokener readFrom) throws JSONException {
/*
* Getting the parser to populate this could get tricky. Instead, just
* parse to temporary JSONArray and then steal the data from that.
*/
Object object = readFrom.nextValue();
if (object instanceof JSONArray) {
values = ((JSONArray) object).values;
} else {
throw JSON.typeMismatch(object, "JSONArray");
}
}
So the tokener does not recognize the object as a JSONArray. I would take a look at your raw response and see if adding a limit doesn't change the response to be an object with a result array inside of it (so that it can also include arguments to help web calls handle paging). Either way, there's something in the format of the response that the tokener does not recognize as being a Json array.
Upon realizing that the PHP script stopped working because too many rows & columns were retrieved instead of * I only Selected data that I truly needed (about 1/3 of all columns), then I added a where clause where ID would be above the number I sent from post and I keep repeating the script until finally the response is not "null".
Thank you for everyone who contributed to finding the solution.

Best way to display an email (JavaMail Message) in android

I am building an android email client app. I managed to display the emails headers/senders in a RecylerView. Next, I want to start a new activity that will display the email content/attachments when the user chooses a specific mail.
I have a hard time doing this through intents. I am able to get the contents of the email (text, inline images, attachments) but I can't figure out a way to display them as close to the original format as possible. I thought of putting the text in a StringBuilder and sending it through an intent in order to display the text, but this way I can't display the inline images in the right place and there are also formatting problems.
Any kind of guidance towards the way I should approach this is much appreciated.
The class that displays the list of the available mails and gets the content of the specific mail to send it another activity for displaying it. I know the code is a little hazardous, I tried many approaches and it is far from the final form.
public class CheckMail extends Activity {
static List<Message> messages = new ArrayList<>();
String[] sender;
String[] date;
String[] subject;
boolean[] seen;
Context context = null;
ListView listView;
Intent intent;
Store store;
StringBuilder content = new StringBuilder();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check_mail);
if (android.os.Build.VERSION.SDK_INT > 9)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
context = this;
ReadEmails task = new ReadEmails();
task.execute();
}
public void writePart(Part p) throws Exception {
if (p instanceof Message)
this.writeEnvelope((Message) p);
//check if the content is plain text
if (p.isMimeType("text/plain")) {
content.append(p.getContent().toString());
}
//check if the content has attachment
else if (p.isMimeType("multipart/*")) {
System.out.println("This is a Multipart");
System.out.println("---------------------------");
Multipart mp = (Multipart) p.getContent();
int count = mp.getCount();
for (int i = 0; i < count; i++)
writePart(mp.getBodyPart(i));
}
//check if the content is a nested message
else if (p.isMimeType("message/rfc822")) {
System.out.println("This is a Nested Message");
System.out.println("---------------------------");
writePart((Part) p.getContent());
}
/*
//check if the content is an inline image
else if (p.isMimeType("image/jpeg")) {
System.out.println("--------> image/jpeg");
Object o = p.getContent();
InputStream x = (InputStream) o;
// Construct the required byte array
System.out.println("x.length = " + x.available());
while ((i = (int) ((InputStream) x).available()) > 0) {
int result = (int) (((InputStream) x).read(bArray));
if (result == -1)
int i = 0;
byte[] bArray = new byte[x.available()];
break;
}
FileOutputStream f2 = new FileOutputStream("/tmp/image.jpg");
f2.write(bArray);
}
else if (p.getContentType().contains("image/")) {
System.out.println("content type" + p.getContentType());
File f = new File("image" + new Date().getTime() + ".jpg");
DataOutputStream output = new DataOutputStream(
new BufferedOutputStream(new FileOutputStream(f)));
com.sun.mail.util.BASE64DecoderStream test =
(com.sun.mail.util.BASE64DecoderStream) p
.getContent();
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = test.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
}
else {
Object o = p.getContent();
if (o instanceof String) {
System.out.println("This is a string");
System.out.println("---------------------------");
System.out.println((String) o);
}
else if (o instanceof InputStream) {
System.out.println("This is just an input stream");
System.out.println("---------------------------");
InputStream is = (InputStream) o;
is = (InputStream) o;
int c;
while ((c = is.read()) != -1)
System.out.write(c);
}
else {
System.out.println("This is an unknown type");
System.out.println("---------------------------");
System.out.println(o.toString());
}
}
*/
}
public void writeEnvelope(Message m) throws Exception {
System.out.println("This is the message envelope");
System.out.println("---------------------------");
Address[] a;
StringBuilder sender = new StringBuilder();
StringBuilder recipients = new StringBuilder();
String subject = "";
// FROM
if ((a = m.getFrom()) != null) {
for (int j = 0; j < a.length; j++)
sender.append(a[j].toString());
}
// TO
if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
for (int j = 0; j < a.length; j++)
recipients.append(a[j].toString());
}
// SUBJECT
if (m.getSubject() != null)
subject = m.getSubject();
intent.putExtra("Sender", sender.toString());
intent.putExtra("Recipients", recipients.toString());
intent.putExtra("Message", subject);
intent.putExtra("Date", m.getReceivedDate().toString());
}
class ReadEmails extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// Create all the needed properties - empty!
Properties connectionProperties = new Properties();
// Create the session
Session session = Session.getDefaultInstance(connectionProperties, null);
try {
System.out.print("Connecting to the IMAP server...");
// Connecting to the server
// Set the store depending on the parameter flag value
store = session.getStore("imaps");
// Set the server depending on the parameter flag value
String server = "imap.gmail.com";
store.connect(server, "....#gmail.com", "password");
System.out.println("done!");
// Get the Inbox folder
Folder inbox = store.getFolder("Inbox");
// Set the mode to the read-only mode
inbox.open(Folder.READ_ONLY);
// Get messages
CheckMail.messages = Arrays.asList(inbox.getMessages());
System.out.println("Reading messages...");
sender = new String[messages.size()];
date = new String[messages.size()];
subject = new String[messages.size()];
seen = new boolean[messages.size()];
for (int i = 0; i < messages.size(); i++) {
try {
Address[] froms = messages.get(i).getFrom();
String email = froms == null ? null : ((InternetAddress) froms[0]).getAddress();
sender[i] = email;
date[i] = messages.get(i).getReceivedDate().toString();
subject[i] = messages.get(i).getSubject();
Flags flags = messages.get(i).getFlags();
Flags.Flag[] sf = flags.getSystemFlags();
for (int j = 0; j < sf.length; j++) {
if (sf[j] == Flags.Flag.SEEN)
seen[i] = true;
else
seen[i] = false;
}
} catch (MessagingException e) {
e.printStackTrace();
}
}
System.out.println("Done reading...");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
CustomListAdapter whatever = new CustomListAdapter((Activity) context, sender, date, subject, seen);
listView = (ListView) findViewById(R.id.listviewID);
listView.setAdapter(whatever);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
try {
content.delete(0, content.length());
intent = new Intent(context, OpenMail.class);
writePart(messages.get(position));
intent.putExtra("Content", content.toString());
startActivity(intent);
}
catch (Exception e)
{e.printStackTrace();}
}
});
}
}
}
Since no one answered...I display emails via Javamail in some of my apps.
I think you're on the right track, having separate activities for the list and viewer is a good approach. [Or separate fragments because on a tablet you may want to display the list and the body on the same screen, side by side]
Couple issues that might come up:
I would be cautious about putting the email content in an extra to start the activity and/or committing it to saved instance state in the viewer activity because there are size limits [For example, 1MB for saved instance state on Android 7+]
Downloading the email in a ASyncTask in the activity might not be the best approach. I don't know the full purpose of the app, but I assume that is something that should succeed whether the user waits or not? The ASyncTask will continue to run if they task away, but it will hold on to the activity context causing a so called 'temporary memory leak'. It is probably best to put it in a service and download it in a separate thread. However, doing it in the activity as a proof of concept is perfectly reasonable...
I don't think that walking the message structure in the email list activity is the best approach. In my apps, I download email in a background service and commit the data to an SQL-DB via a ContentProvider. On the message viewer screen the email body is retrieved from the ContentProvider/SQL-DB using a component called the CursorLoader. It handles all the loading in the background so that the UI remains responsive whilst loading large mails. But in any event, I avoid passing the message body between activities.
A lot of emails have HTML parts (multipart/alternative: text/plain & text/html) so the viewer was implemented as a WebView. The WebView produced good looking emails with minimal effort.
Couple miscellaneous gotchas, when retrieving the mail, take care to call setPeek(true). It will stop the the READ flag being set. It is not an issue for GMail, but some IMAP servers will set this flag. Users will complain if any app other than their primary email app changes the READ flag. Also don't assume that any of the headers are present, SPAM emails are notorious for leaving out the message ID, subject and other fields. Finally, it might be worth considering implementing authentication via OAuth2 which will enable your app to connect to a user's GMail account via Javamail without needing their password.
I'm not sure that any of that really helps because it is a pretty big job, but one step at a time...Cheers!

Interesting issue with POST requests (HttpURLConnection) - But why does it happen?

So I just spent 6 hours worth of work, figuring out this 'little' fact:
Without calling client.getResponseCode() THE POST REQUEST DOES NOT GO THROUGH.
I hope that someone can explain why!
Specifically, for this minimalistic android client standalone code literally nothing happens without the line int status = client.getResponseCode();
but with it,everything works like magic.
I didn't find any official documentation about this, so I'm wondering what's up, or what I don't understand (The people implementing Java usually do outstanding job, so it's probably me not getting something :) ).
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final String theUrl = "http://xx.yyy.zz.aa:bb/securitiesFollowServer/users";
final String TAG = getClass().getSimpleName();
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
String body = "BODY OF MESSAGE";
HttpURLConnection client = null;
BufferedWriter outputPost = null;
try {
URL url = new URL(theUrl);
// open the connection
client = (HttpURLConnection) url.openConnection();
client.setRequestProperty("content-type", "text/plain");
//client.setRequestMethod("POST"); Someone claimed that setDoOutput(true) works so I will try that instead (I tried both,mutually and exclusively so all 3 options).
client.setDoOutput(true);
outputPost = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
outputPost.write(body);
outputPost.flush();
outputPost.close();
int status = client.getResponseCode();
StackTraceElement[] r = Thread.currentThread().getStackTrace();
String toNotepad = "";
for (int i = 0; i < r.length; ++i) {
toNotepad += '\n' + String.valueOf(i) + '.' + ':' + r[i].toString();
}
// This is where I set a breakpoint and got the stacktrace value from toNotepad,and copy pasted it.
} catch (IOException e) {
Log.e(TAG, "Error ", e);
} finally {
if (client != null) {
client.disconnect();
}
if (outputPost != null) {
try {
outputPost.close();
} catch (IOException e) {
Log.e(TAG, "IO ERROR");
}
}
return null;
}
}
};
task.execute();
}
}
For completeness of the question, here is the "server side" minimalistic code
#POST
#Consumes(MediaType.TEXT_PLAIN)
#Produces(MediaType.TEXT_PLAIN)
public String setDebugResource(String a){
return "I got this string:"+a;}
And here is the stacktrace (I made it obvious in the code above where exactly I copy-pasted its value):
When not working(or working, it is exactly the same stacktrace).:
0.:dalvik.system.VMStack.getThreadStackTrace(Native Method)
1.:java.lang.Thread.getStackTrace(Thread.java:580)
2.:dor.only.dorking.android.apppostrequest.MainActivity$1.doInBackground(MainActivity.java:52)
3.:dor.only.dorking.android.apppostrequest.MainActivity$1.doInBackground(MainActivity.java:28)
4.:android.os.AsyncTask$2.call(AsyncTask.java:292)
5.:java.util.concurrent.FutureTask.run(FutureTask.java:237)
6.:android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
7.:java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
8.:java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
9.:java.lang.Thread.run(Thread.java:818)
According to the HttpUrlConnection docs you must call setDoOutput(true) on the client object instead of setting the method to POST. The method will be set automatically to POST through this. They have an example under section "Posting Content".
There's an example here as well and a larger discussion here
Frankly, I would skip using the raw HttpUrlConnection class and use something like Volley.

Permissions Error - Trying to get friends using android facebook sdk

I am trying to add a feature to my android app that allows users to "checkin" with other people tagged to the checkin.
I have the checkins method working no problem and can tag some one by adding the user ID as a parameter (see code below)
public void postLocationTagged(String msg, String tags, String placeID, Double lat, Double lon) {
Log.d("Tests", "Testing graph API location post");
String access_token = sharedPrefs.getString("access_token", "x");
try {
if (isSession()) {
String response = mFacebook.request("me");
Bundle parameters = new Bundle();
parameters.putString("access_token", access_token);
parameters.putString("place", placeID);
parameters.putString("Message",msg);
JSONObject coordinates = new JSONObject();
coordinates.put("latitude", lat);
coordinates.put("longitude", lon);
parameters.putString("coordinates",coordinates.toString());
parameters.putString("tags", tags);
response = mFacebook.request("me/checkins", parameters, "POST");
Toast display = Toast.makeText(this, "Checkin has been posted to Facebook.", Toast.LENGTH_SHORT);
display.show();
Log.d("Tests", "got response: " + response);
if (response == null || response.equals("") ||
response.equals("false")) {
Log.v("Error", "Blank response");
}
} else {
// no logged in, so relogin
Log.d(TAG, "sessionNOTValid, relogin");
mFacebook.authorize(this, PERMS, new LoginDialogListener());
}
} catch(Exception e) {
e.printStackTrace();
}
}
This works fine (I've posted it in case it is of help to anyone else!), the problem i am having is i am trying to create a list of the users friends so they can select the friends they want to tag. I have the method getFriends (see below) which i am then going to use to generate an AlertDialog that the user can select from which in turn will give me the id to use in the above "postLocationTagged" method.
public void getFriends(CharSequence[] charFriendsNames,CharSequence[] charFriendsID, ProgressBar progbar) {
pb = progbar;
try {
if (isSession()) {
String access_token = sharedPrefs.getString("access_token", "x");
friends = charFriendsNames;
friendsID = charFriendsID;
Log.d(TAG, "Getting Friends!");
String response = mFacebook.request("me");
Bundle parameters = new Bundle();
parameters.putString("access_token", access_token);
response = mFacebook.request("me/friends", parameters, "POST");
Log.d("Tests", "got response: " + response);
if (response == null || response.equals("") ||
response.equals("false")) {
Log.v("Error", "Blank response");
}
} else {
// no logged in, so relogin
Log.d(TAG, "sessionNOTValid, relogin");
mFacebook.authorize(this, PERMS, new LoginDialogListener());
}
} catch(Exception e) {
e.printStackTrace();
}
}
When i look at the response in the log it reads:
"got responce: {"error":{"type":"OAuthException", "message":"(#200) Permissions error"}}"
I have looked through the graphAPI documentation and searched for similar questions but to no avail! I'm not sure if i need to request extra permissions for the app or if this is something your just not allowed to do! Any help/suggestions would be greatly appreciated.
You might need the following permissions:
user_checkins
friends_checkins
read_friendlists
manage_friendlists
publish_checkins
Check the related ones from the API docs. Before that, make sure that which line causes this permission error and try to fix it.
The solution is to implement a RequestListener when making the request to the Facebook graph API. I have the new getFriends() method (see below) which uses the AsyncGacebookRunner to request the data.
public void getFriends(CharSequence[] charFriendsNames,String[] sFriendsID, ProgressBar progbar) {
try{
//Pass arrays to store data
friends = charFriendsNames;
friendsID = sFriendsID;
pb = progbar;
Log.d(TAG, "Getting Friends!");
//Create Request with Friends Request Listener
mAsyncRunner.request("me/friends", new FriendsRequestListener());
} catch (Exception e) {
Log.d(TAG, "Exception: " + e.getMessage());
}
}
The AsyncFacebookRunner makes the the request using the custom FriendsRequestListener (see below) which implements the RequestListener class;
private class FriendsRequestListener implements RequestListener {
String friendData;
//Method runs when request is complete
public void onComplete(String response, Object state) {
Log.d(TAG, "FriendListRequestONComplete");
//Create a copy of the response so i can be read in the run() method.
friendData = response;
//Create method to run on UI thread
FBConnectActivity.this.runOnUiThread(new Runnable() {
public void run() {
try {
//Parse JSON Data
JSONObject json;
json = Util.parseJson(friendData);
//Get the JSONArry from our response JSONObject
JSONArray friendArray = json.getJSONArray("data");
//Loop through our JSONArray
int friendCount = 0;
String fId, fNm;
JSONObject friend;
for (int i = 0;i<friendArray.length();i++){
//Get a JSONObject from the JSONArray
friend = friendArray.getJSONObject(i);
//Extract the strings from the JSONObject
fId = friend.getString("id");
fNm = friend.getString("name");
//Set the values to our arrays
friendsID[friendCount] = fId;
friends[friendCount] = fNm;
friendCount ++;
Log.d("TEST", "Friend Added: " + fNm);
}
//Remove Progress Bar
pb.setVisibility(ProgressBar.GONE);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FacebookError e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
Feel free to use any of this code in your own projects, or ask any questions about it.
You can private static final String[] PERMISSIONS = new String[] {"publish_stream","status_update",xxxx};xxx is premissions

Categories

Resources