Running HTTP Request in seperate Thread not working - java

I have been trying to get some very simple code to work which should read an online file and print the contents of that file in the log. At first I didn't know that it needed to be handled in a seperate thread so I left it in the onCreate Method. Now I put it into a seperate Thread with the help of this question: How to use separate thread to perform http requests but the app still crashes! Since I'm desperate to get this working so I can keep on learning how to program this app, I will insert the exact code I used:
package com.dan6erbond.schoolhelper;
import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
private String link = "https://dan6erbond.github.io/I1A/Documents/Zusammenfassungen/Zusammenfassungen.json";
String content;
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
Log.i("TAG", content);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread downloadFile = new Thread(new Runnable(){
#Override
public void run(){
try {
URL url = new URL(link);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
String str;
while ((str = in.readLine()) != null) {
content += str;
}
Log.i("TAG", content);
in.close();
} catch (Exception e) {
Log.i("TAG", "Error occured!");
}
handler.sendEmptyMessage(0);
}
});
downloadFile.start();
}
}
In the log the error message is being sent:
01-05 07:40:33.320 9601-9622/com.dan6erbond.schoolhelper I/TAG: Error occured!
I'd be really happy if someone could help me with this problem. It's probably very simple but I just started coding in Android Studio so I'm really new to this.

I just needed to add the INTERNET permission. I figured that out by printing the error message:
Log.i("TAG", e.getMessage());
Which resulted in this:
01-05 08:05:10.806 11815-11838/com.dan6erbond.schoolhelper I/TAG: Permission denied (missing INTERNET permission?)
I just added this to the Android Manifest:
<uses-permission android:name="android.permission.INTERNET"/>
Thanks everyone for your help!

Related

New to okhttp3, no idea why it won't show the results on TextView

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.StrictMode;
import android.widget.TextView;
import java.io.File;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.OkHttpClient;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
final TextView textView = findViewById(R.id.text_view_id);
final String IMAGE1 = "storage/emulated/0/Download/image_1.jpeg";
File file1 = new File(IMAGE1);
try {
final MediaType MEDIA_TYPE_JPEG = MediaType.parse("image/jpeg");
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("images", "image_1.jpeg",
RequestBody.create(file1, MEDIA_TYPE_JPEG))
.addFormDataPart("organs", "flower")
.build();
Request request = new Request.Builder()
.url("https://my-api.plantnet.org/v2/identify/all?api-key=123")
.post(requestBody)
.build();
OkHttpClient client = new OkHttpClient();
Response response = client.newCall(request).execute();
textView.setText(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
}
I understand that I'm trying to run a network activity here on the main thread. That's why I included the StrictMode permitAll thing to get around the issue (I saw an answer to a similar topic that suggested doing so). I am trying to use the PlantNet API here and I use my phone for testing. The same phone where the image is saved.
go see retrofit
it provides a nice and easy way to make your network calls off the main thread

Android internet access throws IOException

I am trying to write an app that pings a web page, which will then trigger an action.
package com.anton.lightcontrol;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Switch;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
public class MainActivity extends AppCompatActivity {
Switch onOffSwitch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
onOffSwitch = (Switch) findViewById(R.id.onOffSwitch);
onOffSwitch.setChecked(true);
onOffSwitch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (onOffSwitch.isChecked()==true) {
onOffSwitch.setTextColor(Color.GREEN);
LightConnection("http://raspberrypi/toggle_on.py");
}
else if (onOffSwitch.isChecked()==false){
onOffSwitch.setTextColor(Color.RED);
LightConnection("http://raspberrypi/toggle_off.py");
}
}
});
}
private void LightConnection(final String accessUrl){
(new Thread(new Runnable() {
#Override
public void run() {
try{
Log.d("EXEC", "#1");
URL url = new URL(accessUrl);
Log.d("EXEC", "#2");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
Log.d("EXEC", "#3");
InputStreamReader input = new InputStreamReader(conn.getInputStream(), "utf-8");
Log.d("EXEC", "#4");
BufferedReader reader = new BufferedReader(input,2000);
Log.d("EXEC", "#5");
String line = reader.readLine();
Log.d("EXEC", "#6");
}
catch (IOException e){
Log.d("EXEC", "#10 - CATCH");
onOffSwitch.setTextColor(Color.YELLOW);
}
}
})).start();
}
}
My debug output looks like the following:
D/EXEC: #1
D/EXEC: #2
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/EXEC: #3
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
D/EXEC: #10 - CATCH
I have been searching for a solution for the isSBSettingEnabled false error, but I couldn't find anything that helped me.
I am running my app on a Samsung M20 smartphone.
This technically isn't an error, since it's alerting you that you're not using a network security config. More information on this here: Network security configuration: Android Developer Docs.
However, if you're limited to using HTTP, you can resolve connection issues by permitting cleartext traffic by adding this to your <application> tag in AndroidManifext.xml:
android:usesCleartextTraffic="true"

Can't getApplicationContext. because java.lang.NullPointerException

I want make mechanism that I can call from any place in app to write in file.
I make next class:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import android.content.Context;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import android.app.Activity;
import android.os.Environment;
import android.util.Log;
import android.content.Context;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class LogFile extends Activity {
public void writeFile(String msg)
{
Log.d("writeFile", "writeToFile");
try {
Context context = getApplicationContext();
FileOutputStream fos = context.openFileOutput("log.txt", Context.MODE_PRIVATE);
OutputStreamWriter osw = new OutputStreamWriter(fos);
BufferedWriter outputStream = new BufferedWriter(osw);
outputStream.write(msg);
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.d("writeFile", "File not found");
} catch (NullPointerException e) {
e.printStackTrace();
Log.d("writeFile", "NullPointerException");
} catch (IOException e) {
e.printStackTrace();
Log.d("writeFile", "File problems");
}
}
}
But in this line
Context context = getApplicationContext();
I have error
W/System.err: java.lang.NullPointerException
W/System.err: at android.content.ContextWrapper.openFileOutput(ContextWrapper.java:185)
W/System.err: at com.example.tracklogger.LogFile.writeFile(LogFile.java:37)
I'm not sure this is the "right" way to solve your problem or make it work.
I think the problem is that you are passing the value of Activity's context (and this is null, for that reason it throws that Exception) and you need Application's context.
In my personal case, I solved a similar problem as follows:
GlobalVars.java file, containing all "global variables", like Applications context (not Activity's context):
public class GlobalVars extends Application {
public static Context context;
#Override public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
}
Taken from here: Getting the Application Context
Good luck, and happy coding!

Get XML file from url to Android Application

I have a problem to get .xml data from website and parse to android application, i have try many suggestion but never work. It works fine when i open file in assets folder, but when i try to get from url, it show nothing
This is my Activity Class
package com.android.baliweather;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.TextView;
public class Prakiraan extends Activity {
/** Called when the activity is first created. */
private ListView listView;
private TextView judul;
private String URL_MAIN = "http://localhost/android/propinsi_17_1.xml";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.prakiraan_cuaca);
judul = (TextView) findViewById(R.id.menu1);
listView = (ListView) findViewById(R.id.listview);
bindDataToListing();
}
private void bindDataToListing() {
try {
URL url = new URL("http://localhost/android/propinsi_17_1.xml");
URLConnection connection = url.openConnection();
//URLConnection connection = url.openConnection();
//HttpURLConnection httpConnection = (HttpURLConnection)connection;
//InputStream in = httpConnection.getInputStream();
SAXParserFactory saxparser = SAXParserFactory.newInstance();
SAXParser parser = saxparser.newSAXParser();
XMLReader xmlReader = parser.getXMLReader();
XMLParser pc = new XMLParser();
xmlReader.setContentHandler(pc);
//InputStream is = getAssets().open("propinsi_17_1.xml");
//InputStream is = new URL(URL_MAIN).openStream();
xmlReader.parse(new InputSource(connection.getInputStream()));
BindingData bindingData = new BindingData(this, pc.kota, pc.cuaca, pc.suhuMin, pc.suhuMax, pc.kelembapanMin, pc.kelembapanMax, pc.kecepatanAngin, pc.arahAngin);
listView.setAdapter(bindingData);
}
catch (Exception e) {
e.getMessage();
}
}
}
I think the problem only on this class, but i have no idea which one. Please help
It might be android.os.NetworkOnMainThreadException - you're trying to do time-heavy task in a UI thread and the system is preventing you from doing it (you can possibly see this in your logcat). You can implement AsyncTask in order to do it in the background thread.
It may also be that you forgot to add the permission in a manifest file - <uses-permission android:name="android.permission.INTERNET" />

Apk File download Error using Java in Android

.I followed this tutorial and getting errors "PARSING ERROR THERE IS A PROBLEM PARSING THE PACKAGE". I have check the result in Android Device Samsung Galaxy S3.
package com.mrfs.android.surveyapp.activities;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
public class ApkFileAsync extends Activity
{
UpdateApp updateAppInstance;
#Override
public void onCreate(Bundle savedBundleInstance)
{
super.onCreate(savedBundleInstance);
updateAppInstance = new UpdateApp();
updateAppInstance.setContext(getApplicationContext());
updateAppInstance.execute("http://demo.ingresssolutions.com/proposalmanagement/services/user/getApkFile");
}
private class UpdateApp extends AsyncTask<String,Void,Void>{
private Context context;
public void setContext(Context contextf){
context = contextf;
}
#Override
protected Void doInBackground(String... arg0) {
try {
URL url = new URL(arg0[0]);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("POST");
c.setDoOutput(true);
c.connect();
String PATH = "/mnt/sdcard/Download/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file,"surveyapp.apk");
if(outputFile.exists()){
outputFile.delete();
}
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
/* Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File("/mnt/sdcard/Download/update.apk")), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);*/ // without this flag android returned a intent error!
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/" + "app.apk")), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
context.startActivity(intent);
} catch (Exception e) {
Log.e("UpdateAPP", "Update error! " + e.getMessage());
}
return null;
}}
}
I am getting this error after Complete Action using dialog when trying to press either PACKAGE INSTALLER or VERIFY AND INSTALL in both cases same error.
Change your manifes to like
This should work fine i think.. If not worked please post your tutorial link i missed it.. i need to check it.. and i will update answer...
and also mention how you are installing app wether by eclipse or by some other process like importing apk... IF importing apk to real device means please check ur device version, If its s3 mans it has ICS api level includes 14 or 15 so change that.. if its jellly bean means you can use up to 18

Categories