HTTPUrlConnection crashes app on getOutputStream().write (hanging, no Exception thrown) - android

I am trying to write a network functionality for an android application with android studio.
It is very simple. I just try to post some data to an url and fetch data back (all in simple HTTP).
I am testing with the emulator, device is Pixel 2 API 28.
As long as the internet is activated on the emulator everything works fine.
But as soon as i disable the wifi, the application hangs when I try to send the data, and finally crashes. Android offers to stop the application.
It hangs on this call:
urlConnection.getOutputStream().write(postDataBytes);
Documentation and web say, that this method should throw an exception, when there is no internet connection. Especially the UnknownHostException is mentioned very often. But I do not receive any exception.
Where could I go from here?
Here is the code of the whole connection class i use. The doInBackground method is the place where the internet magic happens and the error occures:
package com.example.tf2;
//This class is used for easier networking.
//It is using volley..
import android.content.Context;
/* import android.graphics.Bitmap; */
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.util.Log;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
/* Info about "associative arrays" for the post params taken from Stackoverflow:
https://stackoverflow.com/questions/5122913/java-associative-array
*/
public class mvNetConnect extends AsyncTask<String, Void, String> {
private final String endpoint = "*** here is a valid url ***";
Map<String, String> post_params = new HashMap<String, String>();
String mode = "GET";
String token = "";
private Context useContext;
public mvNetConnect(Context myContext) {
useContext = myContext;
}
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection;
try {
//Daten aus Eingabefeldern auslesen.
//TextView textview_username =
url = new URL(endpoint + urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(1000); // Timeout in Millisekunden. Ansonsten bekommt der Enduser nie eine Antwort..
urlConnection.setReadTimeout(1000);
//Falls wir ein Token haben, fügen wir es dem Request hinzu..
if(token != "") {
urlConnection.addRequestProperty("auth", token);
}
//Falls dies ein Post-Aufruf ist, machen wir auch einen daraus..
StringBuilder postData = new StringBuilder();
if(mode == "POST") {
urlConnection.setRequestMethod("POST");
//Post Parameter hinzufügen (Loop taken from stackoverflow (Thread from harto): https://stackoverflow.com/questions/1066589/iterate-through-a-hashmap)
for (Map.Entry<String, String> entry : post_params.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
// Add Params to request..
if (postData.length() != 0) {
postData.append('&');
}
postData.append(URLEncoder.encode(key, "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(value, "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
urlConnection.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
urlConnection.setDoOutput(true);
urlConnection.getOutputStream().write(postDataBytes);
}
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read(); //Erstes Zeichen lesen.
while(data != -1) { //So lang es Daten gibt.
char current = (char) data; //Zeichen umwandeln.
result += current; //Zeichen an Ausgabe anhängen.
data = reader.read(); //Nächstes Zeichen lesen.
}
} catch(UnknownHostException e) {
Log.i("Info", "error!!!");
} catch(MalformedURLException e) {
Log.i("Info", "no error?");
e.printStackTrace();
return "Failed";
} catch(Exception e) {
Log.i("Info", "errors..");
e.printStackTrace();
return "Failed";
} catch (Throwable throwable) {
// Output unexpected Throwables.
Log.i("info", throwable.toString());
}
Log.i("Info", result.toString());
return result;
}
public void setModeToPost() {
mode = "POST";
}
public void setModeToGet() {
mode = "GET";
}
public void setToken(String _token) {
token = _token;
}
public void addPostParam(String key, String value) {
post_params.put(key, value);
//To extract a key one could use: post_params.get(key);
}
public void clearPostParams(String key, String value) {
post_params.clear();
}
}

Related

QR Code to Google Sheets in Andriod Studio

I have many QR codes ex. Example on imgur, which has peoples' names, numbers, and emails, and I need to scan them. The data comes in something like this: "joe,1234567890,joe#joe.com". I want to write an app that uploads the data to a google sheet and I found a tutorial online from crazycodersclub.com, but when I do the same thing it gives me an error, something like:
Exception: Invalid argument: URL (line 11, file "Code")
Google Script Code
function doGet(e){
var url = encodeUrl("https://docs.google.com/spreadsheets/d/1IEAHcv2n33YO9d7IbfWNVLv2Hl1Q1UXveazPcgMZrMs/edit?usp=sharing/")
var ss = SpreadsheetApp.openByUrl(url);
var sheet = ss.getSheetByName("Sheet1");
return insert(e,sheet);
}
function doPost(e){
var url = encodeUrl("https://docs.google.com/spreadsheets/d/1IEAHcv2n33YO9d7IbfWNVLv2Hl1Q1UXveazPcgMZrMs/edit?usp=sharing/")
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1IEAHcv2n33YO9d7IbfWNVLv2Hl1Q1UXveazPcgMZrMs/edit?usp=sharing/");
var sheet = ss.getSheetByName("Sheet1");
return insert(e,sheet);
}
function insert(e,sheet) {
var scannedData = e.parameter.sdata;
var d = new Date();
var ctime = d.toLocaleString();
sheet.appendRow([scannedData,ctime]);
return ContentService
.createTextOutput("Success")
.setMimeType(ContentService.MimeType.JAVASCRIPT);
}
MainActivity.java
package com.tarbiya.scannerapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import javax.net.ssl.HttpsURLConnection;
public class MainActivity extends AppCompatActivity {
String scannedData;
Button scanBtn;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Activity activity =this;
scanBtn = (Button)findViewById(R.id.scan_btn);
scanBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
IntentIntegrator integrator = new IntentIntegrator(activity);
integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
integrator.setPrompt("Scan");
integrator.setBeepEnabled(false);
integrator.setCameraId(0);
integrator.setBarcodeImageEnabled(false);
integrator.initiateScan();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode,resultCode,data);
if(result!=null) {
scannedData = result.getContents();
if (scannedData != null) {
// Here we need to handle scanned data...
new SendRequest().execute();
}else {
}
}
super.onActivityResult(requestCode, resultCode, data);
}
public class SendRequest extends AsyncTask<String, Void, String> {
protected void onPreExecute(){}
protected String doInBackground(String... arg0) {
try{
//Enter script URL Here
URL url = new URL("https://script.google.com/macros/s/AKfycby_G_K-kmm77peQBSY6xmNZjsDcFIkDgqZwxz6e7guyte5Lxe8/exec");
JSONObject postDataParams = new JSONObject();
//int i;
//for(i=1;i<=70;i++)
// String usn = Integer.toString(i);
//Passing scanned code as parameter
postDataParams.put("sdata",scannedData);
Log.e("params",postDataParams.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader in=new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line="";
while((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
}
else {
return new String("false : "+responseCode);
}
}
catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(), result,
Toast.LENGTH_LONG).show();
}
}
public String getPostDataString(JSONObject params) throws Exception {
StringBuilder result = new StringBuilder();
boolean first = true;
Iterator<String> itr = params.keys();
while(itr.hasNext()){
String key= itr.next();
Object value = params.get(key);
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(key, "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(value.toString(), "UTF-8"));
}
return result.toString();
}
}
If you need to see more code, I can attach some more. It looks basically the same as the one in the tutorial right now.
Thank you so much for your help.
The reason you were receiving the Exception: Invalid argument: URL message is because the url you were passing to the openByUrl was not in the correct format.
If you check the documentation for the openByUrl method here, you can see the accepted format of the link.
https://docs.google.com/spreadsheets/d/abc1234567/edit
In your situation, you will have to remove the part after the /edit.
Reference
Apps Script SpreadsheetApp Class - openByUrl(url).

How do i send post request to a webservice?

I follow this post http://hmkcode.com/android-send-json-data-to-server/ and some functions is depreciated. I like to understand how I send an information to a web service.
I try to update the post but i got some mistake.. I know my code has some mistake My code is:
enter code here
package com.example.paulo.myapp.POST;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.paulo.myapp.R;
import com.facebook.internal.BundleJSONConverter;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class Post_Dados extends AppCompatActivity implements View.OnClickListener {
TextView isconected;
EditText customer, pais, twitter;
Button btn_enviar;
String person, country, tw;
static Dados dados;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post__dados);
/* recupera as views */
isconected = (TextView) findViewById(R.id.conected);
customer = (EditText) findViewById(R.id.customer);
pais = (EditText) findViewById(R.id.pais);
twitter = (EditText) findViewById(R.id.twitter);
btn_enviar = (Button) findViewById(R.id.sendWS);
/* checa se está conectado */
if (isConnected()) {
isconected.setText("Conectado !!!!");
}
else {
isconected.setText("Não conectado!!!");
}
/* click do botão */
btn_enviar.setOnClickListener(this);
}
private boolean isConnected() {
ConnectivityManager cm = (ConnectivityManager ) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if ( info != null && info.isConnected()){
return true;
}
else { return false; } }
#Override
public void onClick(View view) {
String c = customer.getText().toString();
String p = pais.getText().toString();
String t = twitter.getText().toString();
if ( c.equals("") || p.equals("") || t.equals("") )
{
Toast.makeText(getBaseContext(), "Preenche os campos os dados!", Toast.LENGTH_LONG).show();
}
else{
new HttpAsyncTask().execute("http://hmkcode.appspot.com/jsonservlet");
}
}
/*metodo de conexao */
private static String POST(String url, String person) throws IOException, JSONException {
InputStream inputStream = null;
String result = "";
try{
/* 1. cria o httpClient */
URL endWeb = new URL(url);
HttpURLConnection con = (HttpURLConnection) endWeb.openConnection();
// 2. configurando o POST
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setUseCaches(false);
con.setRequestProperty("Accept", "application/json");
//3. define enviar e receber
con.setDoOutput(true);
con.setDoInput(true);
//4.faz a conexao
con.connect();
//5. Objeto json
String json = " ";
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("name",dados.getNome());
jsonObject.accumulate("country", dados.getEmail());
jsonObject.accumulate("twitter", dados.getTwitter());
//6.connverte json to json string
json = jsonObject.toString();
// Escreve o objeto JSON usando o OutputStream da requisição:
OutputStream outputStream = con.getOutputStream();
outputStream.write(json.getBytes("UTF-8"));
}
catch (Exception e){
throw e;
}
return "ok";
}
private class HttpAsyncTask extends AsyncTask<String, Void, String>{
String result;
#Override
protected String doInBackground(String... urls) {
dados = new Dados(person.toString(), country.toString(), tw.toString());
try {
result = POST(urls[0], person);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return result;
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Dados enviados!", Toast.LENGTH_LONG).show();
}
}
}
I this url http://hmkcode.appspot.com/post-json/index.html is to check it´s ok.
I like a help to get it ok.
Unfortunately sending HTTP requests in Android is quite the pain without using 3rd party libraries. Fortunately retrofit is awesome and is very widely used. There are a lot tutorials for it, you might try this one for example.

get JSON Array from local server in android 6.0 with HttpURLConnection

I am trying to get a JSON Array from this local server for five days:
localhost/match_picture/service.php?action=read
and i can't do it !!
I search it in google and read too many documentations !
here is my code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class WebService {
public static String readUrl(String server_url) {
BufferedReader bufferedReader = null;
try {
URL url = new URL(server_url);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json+"\n");
}
return sb.toString();
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
and it's Main_Activity:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class Activity_main extends AppCompatActivity {
private ArrayList<StructAcount> netAcount = new ArrayList<StructAcount>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String result= WebService.readUrl("http://localhast/match_picture/service.php?action=read");
if (result != null) {
try {
JSONArray tasks = new JSONArray(result);
for (int i=0; i<tasks.length(); i++) {
StructAcount acount= new StructAcount();
JSONObject object = tasks.getJSONObject(i);
acount.id = object.getLong("user_id");
acount.name = object.getString("user_name");
acount.email = object.getString("user_email");
netAcount.add(acount);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
for (StructAcount acount: netAcount) {
Toast.makeText(Activity_main.this, "username: " + acount.name + "\n" + "useremail: " + acount.email , Toast.LENGTH_SHORT).show();
}
}
}
it is runing on emulator and crashes in this line:
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
and i dont know why ...
I am Searching for five days!!!!
I can do it with HttpClient
but i want to be update
I saw a vidoe in youtube that create a class in Main_Activity extends AsyncTask and make connenction in doInBackground(String... params). I try that and that works correcly. but because I want to do it in anoder class (WebService) and I dont know how can i sent result to Main_Activity , I remove that class extended from AsyncTask.
thank's for your help
sorry for my poor english
You have a NetworkOnMainThreadException to begin with.
And your app crashes.
Google how to solve it.

UnknownHostException WebDav JackRabbit

I'm trying to implement a WebDav client in Android. For this purpose, I'm using a version of JackRabbit modified for Android that I got here (version 2.2.6).
I want to connect to my account in box.com and upload a file. Sincerely, I don't mind box or any other, i just happened to use this one.
Well, continuing with box.com, according to (this link)[https://support.box.com/hc/en-us/articles/200519748-Does-Box-support-WebDAV-] I should used "https://dav.box.com/dav" as server.
I have followed these links to build my code:
http://jackrabbit.apache.org/api/2.1/org/apache/jackrabbit/webdav/client/methods/package-summary.html
http://wiki.apache.org/jackrabbit/WebDAV
I'm getting an UnknownHostException sayingo my the URL I'm using for the server ("https://dav.box.com/dav") couldn't be found.
Any idea why does it not work? Otherwise, have you tried with other server and succeeded?
My code is here:
Thread t = new Thread() {
public void run(){
try {
String uri = "https://app.box.com/files";
HostConfiguration hostConfig = new HostConfiguration();
hostConfig.setHost(uri);
HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
HttpConnectionManagerParams params = new HttpConnectionManagerParams();
int maxHostConnections = 20;
params.setMaxConnectionsPerHost(hostConfig, maxHostConnections);
connectionManager.setParams(params);
HttpClient client = new HttpClient(connectionManager);
client.setHostConfiguration(hostConfig);
Credentials creds = new UsernamePasswordCredentials("USER", "PASSWORD");
client.getState().setCredentials(AuthScope.ANY, creds);
String baseUrl = "/";
File f = new File(Environment.getExternalStorageDirectory() + "/working-draft.txt");
PutMethod method = new PutMethod(baseUrl + "/" + f.getName());
RequestEntity requestEntity = new InputStreamRequestEntity(
new FileInputStream(f));
method.setRequestEntity(requestEntity);
client.executeMethod(method);
}
catch (FileNotFoundException fnfe){
Log.i("SERVICE", "FileNotFoundException");
}
catch (HttpException he){
Log.i("SERVICE", "HttpException");
}
catch (IOException ioe){
Log.i("SERVICE", "IOException");
}
catch (Exception e){
Log.i("SERVICE", "Other Exception");
}
}
};
t.start();
I tried for a long time with JackRabbit and another webDav library but could not get it to work. This is how I eventually managed to send images to a WebDav hosted in IIS7 on a windows server. Hope this helps somebody.
SendImage.java
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.NTCredentials;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.FileEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import ntlm.NTLMSchemeFactory;
//import org.apache.http.client.HttpClient;
public class SendImage extends AsyncTask<String, Context, String> {
Context cxt;
public SendImage(Context cxtIn){
cxt = cxtIn;
}
#Override
protected String doInBackground(String... params) {
if (!Globals.sendImagesBeingPerformed) {
Globals.sendImagesBeingPerformed = true;
String filepath = cxt.getExternalFilesDir("/MyFileStorage/qrscans/").getAbsolutePath();
File myExternalFile = new File(filepath.toString());
File[] sdDirList = myExternalFile.listFiles();
if(sdDirList != null && sdDirList.length>0){
for(int x=0;x<sdDirList.length;x++){
if(sdDirList[x].toString().endsWith(".jpg")){
File myExternalFile2 = new File(cxt.getExternalFilesDir("/MyFileStorage/qrscans/"), sdDirList[x].getName());
//String URL="";
System.out.println("SENDING QR4");
if(myExternalFile2.exists()) {
System.out.println("ScannedExists");
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getAuthSchemes().register("ntlm", new NTLMSchemeFactory());
String url = Globals.getWebDavUrl().trim();
String u = Globals.getWebDavUser().trim();
String p = Globals.getWebDavPass().trim();
String d = Globals.getWebDavDomain().trim();
if(d!=null && !d.isEmpty() && (d.length()>0)){
//use value of d as domain
}else{
//use a space as domain
d = " ";
}
String device = Globals.deviceId;
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(null, -1),
new NTCredentials(u, p, device, d));
HttpConnectionParams.setConnectionTimeout(httpclient.getParams(),5000);
if(url.endsWith("/") || url.endsWith("\\")){
url = url.substring(0, url.length()-1);
}
HttpPut put = new HttpPut(url.trim()+"/"+sdDirList[x].getName());
put.setEntity(new FileEntity(sdDirList[x],"application/octet-stream"));
HttpResponse response = null;
try {
response = httpclient.execute(put);
}catch(Exception e){
return "Error Sending Image:\n"+e.getMessage()+" " + e.getCause();
}
System.out.println("execute done");
BufferedReader in = null;
String webResponse="";
try {
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String stringLine="";
StringBuilder stringBuilder = new StringBuilder();
while ((stringLine = in.readLine()) != null) {
//stringBuilder.append("\n");
stringBuilder.append(stringLine);
}
webResponse=stringBuilder.toString()+"s";
if(webResponse.toString().trim().equalsIgnoreCase("s")){
myExternalFile2.delete();
}
System.out.println("webResponse:" + webResponse);
return null; //webResponse;
}catch(Exception e){
return "Error Sending Image:\n"+e.getMessage()+" " + e.getCause();
}
}
}
}
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
if(result!=null){
Toast.makeText(cxt, result, Toast.LENGTH_LONG).show();
}
Globals.sendImagesBeingPerformed = false;
super.onPostExecute(result);
}
}
NTLMSchemeFactory.java
import org.apache.http.auth.AuthScheme;
import org.apache.http.auth.AuthSchemeFactory;
import org.apache.http.impl.auth.NTLMScheme;
import org.apache.http.params.HttpParams;
public class NTLMSchemeFactory implements AuthSchemeFactory {
public AuthScheme newInstance(final HttpParams params) {
return new NTLMScheme(new JCIFSEngine());
}
}
JCIFSEngine.java
package ntlm;
import java.io.IOException;
import jcifs.ntlmssp.Type1Message;
import jcifs.ntlmssp.Type2Message;
import jcifs.ntlmssp.Type3Message;
import jcifs.util.Base64;
import org.apache.http.impl.auth.NTLMEngine;
import org.apache.http.impl.auth.NTLMEngineException;
public class JCIFSEngine implements NTLMEngine {
public String generateType1Msg(
String domain,
String workstation) throws NTLMEngineException {
Type1Message t1m = new Type1Message(
Type1Message.getDefaultFlags(),
domain,
workstation);
return Base64.encode(t1m.toByteArray());
}
public String generateType3Msg(
String username,
String password,
String domain,
String workstation,
String challenge) throws NTLMEngineException {
Type2Message t2m;
try {
t2m = new Type2Message(Base64.decode(challenge));
} catch (IOException ex) {
throw new NTLMEngineException("Invalid Type2 message", ex);
}
Type3Message t3m = new Type3Message(
t2m,
password,
domain,
username,
workstation,0);
return Base64.encode(t3m.toByteArray());
}
}

JSON parsing error - not parse in google API 4.1 jelly bean

i am working on an app using json parsing...in this parsing is done by json of the given url.
As i run my project on emulator having target = "Google APIs (Google Inc.) - API level 10"
then it runs properly and shows needed results from the target url.
but when run my project on emulator having target = "Google APIs (Google Inc.) - API level 16"
then it shows error and it never parse the given url data and get force close.
i want to make app which run on every API level.
please help...
here's my code:
json parser class:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONArray jObj = null;
static String json = "";
static String req = "POST";
// constructor
public JSONParser() {
}
public JSONArray getJSONFromUrl(String url, String method) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = null;
if(method == req) {
HttpPost httpC = new HttpPost(url);
httpResponse = httpClient.execute(httpC);
}else {
HttpGet httpC = new HttpGet(url);
httpResponse = httpClient.execute(httpC);
}
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONArray(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Another class using json parser class snd fetch data:
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
public class showData extends ListActivity{
public static String url = "http://something/something/";
public static final String TAG_A = "a";
public static final String TAG_B = "b";
public static final String TAG_C = "c";
public static final String TAG_D = "d";
public static final String TAG_E = "e";
public static final String TAG_F = "f";
public static final String GET = "get";
JSONArray Data1 = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
EditText editext_text = (EditText) findViewById(R.id.et);
String urlnew = url + editext_text.getText().toString();
Log.d("url", urlnew);
JSONParser jParser = new JSONParser();
// getting JSON string from URL
area1 = jParser.getJSONFromUrl(urlnew, GET);
Log.d("Json String", area1.toString());
try {
for(int i = 0; i < area1.length(); i++){
JSONObject c = area1.getJSONObject(i);
// Storing each json item in variable
String a = c.getString(TAG_A);
String b = c.getString(TAG_B);
String c = c.getString(TAG_C);
String d = c.getString(TAG_D);
String e = c.getString(TAG_E);
HashMap<String,String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_A, a);
map.put(TAG_B, b);
map.put(TAG_C, c);
map.put(TAG_D, d);
map.put(TAG_E, e);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.list_item_area,
new String[] { TAG_B, TAG_A, TAG_C, TAG_D, TAG_E }, new int[] {
R.id.b, R.id.a, R.id.c, R.id.d, R.id.e });
setListAdapter(adapter);
}
}
You are getting a NetworkOnMainThreadException because as the name is self-explaining, you are doing network request on UI Thread that will make your application laggy and create an horrible experience.
The exception that is thrown when an application attempts to perform a
networking operation on its main thread.
This is only thrown for applications targeting the Honeycomb SDK or
higher. Applications targeting earlier SDK versions are allowed to do
networking on their main event loop threads, but it's heavily
discouraged. See the document Designing for Responsiveness.
You should use Threads or AsyncTask, do you need some explanations on how to use them?
private class NetworkTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
//DO YOUR STUFF
}
#Override
protected void onPostExecute(String result) {
//Update UI
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
This is Network On Main Thread Exception, You have to use Thread for network connection, because the main thread is UI thread will not give any response for Network connection. Use separate thread for network connection

Categories

Resources