I try to get the data from Web Service that I build with JAX-WS, WSDL and I want to implement in Android ListView.
This is my code in web service that I build on Netbeans.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package in.figures.on.mobile;
import db.koneksi.dbKoneksi;
import java.sql.Statement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import org.json.simple.JSONValue;
/**
*
* #author Setyadi
*/
#WebService()
public class AksesData {
/**
* Web service operation
*/
#WebMethod(operationName = "Lokasiku")
public String Lokasiku(
#WebParam(name = "lon") String lon,
#WebParam(name = "lat") String lat) {
//TODO write your implementation code here:
dbKoneksi con = new dbKoneksi();
Statement statement;
String sql = "SELECT desa "
+ "FROM dki "
+ "WHERE ST_Within(ST_SetSRID(ST_MakePoint("+lon+","+lat+"),0),geom);";
ResultSet hasil;
String desa = null;
try{
statement = con.getConnection().createStatement();
hasil = statement.executeQuery(sql);
hasil.next();
desa = hasil.getString(1);
}
catch(Exception e){
desa = "desa_thegagals";
}
finally{
}
if (con != null) {
return desa;
}
else {
return "lokasiku_thegagals";
}
}
/**
* Web service operation
*/
#WebMethod(operationName = "Kategori")
public String Kategori() {
//TODO write your implementation code here:
dbKoneksi con = new dbKoneksi();
Statement statement;
Properties properties;
List list = new ArrayList();
String sql = "SELECT kategori FROM kategori ";
ResultSet hasil;
String kategori = null;
try{
statement = con.getConnection().createStatement();
hasil = statement.executeQuery(sql);
while (hasil.next()) {
properties = new Properties();
properties.put("kategori", hasil.getString(1));
list.add(properties);
}
kategori = JSONValue.toJSONString(list);
}
catch(Exception e){
}
return kategori;
}
}
Does anybody want to help me, at least give me a tutorial about this.
Thanks in advance
Android doesn't provide any support for SOAP web services. They prefer we useRESTful web services with XML or JSON. however there are a few SOAP libraries out there. KSOAP is very popular, I personally have had issues with it. http://ksoap2.sourceforge.net/
Another suggestion is icesoap. it is a very simple library to use and understand, it worked like a charm for me.
http://code.google.com/p/icesoap/
For return data in 2D array
just get the data and convert it into String.
Then store it in Array
rs = s.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
colCount = rsmd.getColumnCount();
String[][] result;
result = new String[size][rsmd.getColumnCount()];
int j=0;
while(rs.next())
{
for (int i = 1; i <= colCount; i++)
{
Object value=null;
if(!rsmd.getColumnTypeName(i).matches("varchar"))
{
if(rsmd.getColumnTypeName(i).matches("decimal"))
value=(Object)rs.getDouble(i);
else
value=(Object)rs.getObject(i);
}
else
{
value = (Object)rs.getString(i);
}
if(value!=null)
{
result[j][i-1]=value.toString();
}
else
{
result[j][i-1]="--";
}
}j++;
}
}
catch (SQLException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and In android phone toy need to get that array and convert it into appropriate data type.
If you going to display it then you can display as it is. No need to convert into its original data type.
Related
I have form that can have variable number of EditText that needs to be validated before form submission. I can perform validation check if EditTexts are fixed in number like following -
Observable<CharSequence> emailObservable = RxTextView.textChanges(editEmail).skip(1);
Observable<CharSequence> passwordObservable = RxTextView.textChanges(editPassword).skip(1);
mFormValidationSubscription = Observable.combineLatest(emailObservable, passwordObservable,
(newEmail, newPassword) -> {
boolean emailValid = !TextUtils.isEmpty(newEmail) && android.util.Patterns.EMAIL_ADDRESS.matcher(newEmail).matches();
if(!emailValid) {
emailInputLayout.setError(getString(R.string.error_invalid_email));
emailInputLayout.setErrorEnabled(true);
}else {
emailInputLayout.setError(null);
emailInputLayout.setErrorEnabled(false);
}
boolean passValid = !TextUtils.isEmpty(newPassword) && newPassword.length() > 4;
if (!passValid) {
passwordInputLayout.setError(getString(R.string.error_invalid_password));
passwordInputLayout.setErrorEnabled(true);
} else {
passwordInputLayout.setError(null);
passwordInputLayout.setErrorEnabled(true);
}
return emailValid && passValid;
}).subscribe(isValid ->{
mSubmitButton.setEnabled(isValid);
});
But now as there are variable number of inputs I tried creating a list of Observable<CharSequence> and Observable.combineLatest() but I'm stuck as to proceed with that.
List<Observable<CharSequence>> observableList = new ArrayList<>();
for(InputRule inputRule : mMaterial.getRules()) {
View vInputRow = inflater.inflate(R.layout.item_material_input_row, null, false);
StyledEditText styledEditText = ((StyledEditText)vInputRow.findViewById(R.id.edit_input));
styledEditText.setHint(inputRule.getName());
Observable<CharSequence> observable = RxTextView.textChanges(styledEditText).skip(1);
observableList.add(observable);
linearLayout.addView(vInputRow);
}
Observable.combineLatest(observableList,......); // What should go in place of these "......"
How can I perform checks for a valid charsequence for each input field. I looked into flatMap(), map(), filter() methods but I don't know how to use them.
Yes, you process abitrary number of Observables in .combineLatest(), but there is still workaround. I got interested in this problem and came up with following solution- we can store information about some data source - last value and source ID (String and resource id) and tunnell all data into some common pipe. For that we can use PublishSubject. We also need to track connection state, for that we should save Subscription to each source on subscription and sever it when we unsubscribe from that source.
We store last data from each source, so we can tell user what source just emitted new value, callback will only contain source id. User can get last value of any source by source id.
I came up with the following code:
import android.util.Log;
import android.widget.EditText;
import com.jakewharton.rxbinding.widget.RxTextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import rx.Observable;
import rx.Subscription;
import rx.functions.Action1;
import rx.subjects.PublishSubject;
public class MultiSourceCombinator {
String LOG_TAG = MultiSourceCombinator.class.getSimpleName();
/**
* We can't handle arbitrary number of sources by CombineLatest, but we can pass data along
* with information about source (sourceId)
*/
private static class SourceData{
String data = "";
Integer sourceId = 0;
}
/**
* Keep id of source, subscription to that source and last value emitted
* by source. This value is passed when source is attached
*/
private class SourceInfo{
Subscription sourceTracking;
Integer sourceId;
SourceData lastData;
SourceInfo(int sourceId, String data){
this.sourceId = sourceId;
// initialize last data with empty value
SourceData d = new SourceData();
d.data = data;
d.sourceId = sourceId;
this.lastData = d;
}
}
/**
* We can tunnel data from all sources into single pipe. Subscriber can treat it as
* Observable<SourceData>
*/
private PublishSubject<SourceData> dataDrain;
/**
* Stores all sources by their ids.
*/
Map<Integer, SourceInfo> sources;
/**
* Callback, notified whenever source emit new data. it receives source id.
* When notification is received by client, it can get value from source by using
* getLastSourceValue(sourceId) method
*/
Action1<Integer> sourceUpdateCallback;
public MultiSourceCombinator(){
dataDrain = PublishSubject.create();
sources = new HashMap<>();
sourceUpdateCallback = null;
// We have to process data, ccoming from common pipe
dataDrain.asObservable()
.subscribe(newValue -> {
if (sourceUpdateCallback == null) {
Log.w(LOG_TAG, "Source " + newValue.sourceId + "emitted new value, " +
"but used did't set callback ");
} else {
sourceUpdateCallback.call(newValue.sourceId);
}
});
}
/**
* Disconnect from all sources (sever Connection (s))
*/
public void stop(){
Log.i(LOG_TAG, "Unsubscribing from all sources");
// copy references to aboid ConcurrentModificatioinException
ArrayList<SourceInfo> t = new ArrayList(sources.values());
for (SourceInfo si : t){
removeSource(si.sourceId);
}
// right now there must be no active sources
if (!sources.isEmpty()){
throw new RuntimeException("There must be no active sources");
}
}
/**
* Create new source from edit field, subscribe to this source and save subscription for
* further tracking.
* #param editText
*/
public void addSource(EditText editText, int sourceId){
if (sources.containsKey(sourceId)){
Log.e(LOG_TAG, "Source with id " + sourceId + " already exist");
return;
}
Observable<CharSequence> source = RxTextView.textChanges(editText).skip(1);
String lastValue = editText.getText().toString();
Log.i(LOG_TAG, "Source with id " + sourceId + " has data " + lastValue);
// Redirect data coming from source to common pipe, to do that attach source id to
// data string
Subscription sourceSubscription = source.subscribe(text -> {
String s = new String(text.toString());
SourceData nextValue = new SourceData();
nextValue.sourceId = sourceId;
nextValue.data = s;
Log.i(LOG_TAG, "Source " + sourceId + "emits new value: " + s);
// save vlast value
sources.get(sourceId).lastData.data = s;
// pass new value down pipeline
dataDrain.onNext(nextValue);
});
// create SourceInfo
SourceInfo sourceInfo = new SourceInfo(sourceId, lastValue);
sourceInfo.sourceTracking = sourceSubscription;
sources.put(sourceId, sourceInfo);
}
/**
* Unsubscribe source from common pipe and remove it from list of sources
* #param sourceId
* #throws IllegalArgumentException
*/
public void removeSource(Integer sourceId) throws IllegalArgumentException {
if (!sources.containsKey(sourceId)){
throw new IllegalArgumentException("There is no source with id: " + sourceId);
}
SourceInfo si = sources.get(sourceId);
Subscription s = si.sourceTracking;
if (null != s && !s.isUnsubscribed()){
Log.i(LOG_TAG, "source " + sourceId + " is active, unsubscribing from it");
si.sourceTracking.unsubscribe();
si.sourceTracking = null;
}
// source is disabled, remove it from list
Log.i(LOG_TAG, "Source " + sourceId + " is disabled ");
sources.remove(sourceId);
}
/**
* User can get value from any source by using source ID.
* #param sourceId
* #return
* #throws IllegalArgumentException
*/
public String getLastSourceValue(Integer sourceId) throws IllegalArgumentException{
if (!sources.containsKey(sourceId)){
throw new IllegalArgumentException("There is no source with id: " + sourceId);
}
String lastValue = sources.get(sourceId).lastData.data;
return lastValue;
}
public void setSourceUpdateCallback(Action1<Integer> sourceUpdateFeedback) {
this.sourceUpdateCallback = sourceUpdateFeedback;
}
}
And we can use it in UI like this:
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.ButterKnife;
public class EdiTextTestActivity extends Activity {
#BindView(R.id.aet_et1)
public EditText et1;
#BindView(R.id.aet_et2)
public EditText et2;
#BindView(R.id.aet_et3)
public EditText et3;
private MultiSourceCombinator multiSourceCombinator;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_text_test);
ButterKnife.bind(this);
multiSourceCombinator = new MultiSourceCombinator();
multiSourceCombinator.setSourceUpdateCallback(id -> {
Toast.makeText(EdiTextTestActivity.this, "New value from source: " + id + " : " +
multiSourceCombinator.getLastSourceValue(id), Toast.LENGTH_SHORT).show();
});
}
#Override
protected void onPause() {
// stop tracking all fields
multiSourceCombinator.stop();
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
// Register fields
multiSourceCombinator.addSource(et1, R.id.aet_et1);
multiSourceCombinator.addSource(et2, R.id.aet_et2);
multiSourceCombinator.addSource(et3, R.id.aet_et3);
}
}
I have a solution for you without using lambda expressions (as I could not compile it with lambdas).
Use the same operator as you wanted:
public static <T, R> Observable<R> combineLatest(List<? extends Observable<? extends T>> sources, FuncN<? extends R> combineFunction)
Observable.combineLatest(observableList, new FuncN<Boolean>() {
#Override
public Boolean call(Object... objects) {
boolean isValid = true;
CharSequence input;
for (int i = 0; i < objects.length; i++) {
input = (CharSequence) objects[i];
switch (i) {
case 1:
//First text field value
break;
case 2:
//Second text field value
break;
default:
isValid = false;
}
}
return isValid;
}
})
The reason lambda expressions don't work is probably in second parameter of the function combineLatest(...):
public interface FuncN<R> extends Function {
R call(Object... args);
}
According to this post implementing Arbitrary Number of Arguments is hard to do and workarounds need to be created.
RxJava v2 is compatible with Java 8 and has a different implementation of combineLatest
I used R. Zagórski's answer as guide on how to do this with Kotlin
This is what worked for me in the end.
val ob1 = RxTextView.textChanges(field1).skip(1)
val ob2 = RxTextView.textChanges(field2).skip(1)
val ob3 = RxTextView.textChanges(field3).skip(1)
val observableList = arrayListOf<Observable<CharSequence>>()
observableList.add(ob1)
observableList.add(ob3)
val formValidator = Observable.combineLatest(observableList, {
var isValid = true
it.forEach {
val string = it.toString()
if (string.isEmpty()) {
isValid = false
}
}
return#combineLatest isValid
})
formValidator.subscribe { isValid ->
if (isValid) {
//do something
} else {
//do something
}
}
I am afraid that my activity is restarted when i open it through TaskManager....
and my DefaultHttpClient object treated as fresh one..so here i am loosing the
session.
I tried by overriding the onSaveInstanceState() method..but no use..
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState); // the UI component values are saved here.
}
How i can get rid of this one...
when you press button Home, activity will pause and resume when reopen.
you shout put code to onCreate().
see activity lifecryde:
You could subclass Android Applications: You can init the HttpClient there and hold the reference.
Look here
Than you can access from activity your Application object with activity.getApplication()
If your session works with cookies than you may need a persistent cookie storeage (like database or shared preferences):
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import org.apache.http.client.CookieStore;
import org.apache.http.cookie.Cookie;
import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
/**
* A persistent cookie store which implements the Apache HttpClient
* {#link CookieStore} interface. Cookies are stored and will persist on the
* user's device between application sessions since they are serialized and
* stored in {#link SharedPreferences}.
* <p>
*/
public class PersistentCookieStore implements CookieStore {
private static final String COOKIE_PREFS = "CookiePrefsFile";
private static final String COOKIE_NAME_STORE = "names";
private static final String COOKIE_NAME_PREFIX = "cookie_";
private final ConcurrentHashMap<String, Cookie> cookies;
private final SharedPreferences cookiePrefs;
/**
* Construct a persistent cookie store.
*/
public PersistentCookieStore(Context context) {
cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, 0);
cookies = new ConcurrentHashMap<String, Cookie>();
// Load any previously stored cookies into the store
String storedCookieNames = cookiePrefs.getString(COOKIE_NAME_STORE,
null);
if (storedCookieNames != null) {
String[] cookieNames = TextUtils.split(storedCookieNames, ",");
for (String name : cookieNames) {
String encodedCookie = cookiePrefs.getString(COOKIE_NAME_PREFIX
+ name, null);
if (encodedCookie != null) {
Cookie decodedCookie = decodeCookie(encodedCookie);
if (decodedCookie != null) {
cookies.put(name, decodedCookie);
}
}
}
// Clear out expired cookies
clearExpired(new Date());
}
}
#Override
public synchronized void addCookie(Cookie cookie) {
String name = cookie.getName() + cookie.getDomain();
// Save cookie into local store, or remove if expired
if (!cookie.isExpired(new Date())) {
cookies.put(name, cookie);
} else {
cookies.remove(name);
}
// Save cookie into persistent store
SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
prefsWriter.putString(COOKIE_NAME_STORE,
TextUtils.join(",", cookies.keySet()));
prefsWriter.putString(COOKIE_NAME_PREFIX + name,
encodeCookie(new SerializableCookie(cookie)));
prefsWriter.commit();
}
#Override
public synchronized void clear() {
// Clear cookies from persistent store
SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
for (String name : cookies.keySet()) {
prefsWriter.remove(COOKIE_NAME_PREFIX + name);
}
prefsWriter.remove(COOKIE_NAME_STORE);
prefsWriter.commit();
// Clear cookies from local store
cookies.clear();
}
#Override
public synchronized boolean clearExpired(Date date) {
boolean clearedAny = false;
SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
for (ConcurrentHashMap.Entry<String, Cookie> entry : cookies.entrySet()) {
String name = entry.getKey();
Cookie cookie = entry.getValue();
if (cookie.isExpired(date)) {
// Clear cookies from local store
cookies.remove(name);
// Clear cookies from persistent store
prefsWriter.remove(COOKIE_NAME_PREFIX + name);
// We've cleared at least one
clearedAny = true;
}
}
// Update names in persistent store
if (clearedAny) {
prefsWriter.putString(COOKIE_NAME_STORE,
TextUtils.join(",", cookies.keySet()));
}
prefsWriter.commit();
return clearedAny;
}
#Override
public synchronized List<Cookie> getCookies() {
return new CopyOnWriteArrayList<Cookie>(cookies.values());
}
//
// Cookie serialization/deserialization
//
protected synchronized String encodeCookie(SerializableCookie cookie) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
ObjectOutputStream outputStream = new ObjectOutputStream(os);
outputStream.writeObject(cookie);
} catch (Exception e) {
return null;
}
return byteArrayToHexString(os.toByteArray());
}
protected synchronized Cookie decodeCookie(String cookieStr) {
byte[] bytes = hexStringToByteArray(cookieStr);
ByteArrayInputStream is = new ByteArrayInputStream(bytes);
Cookie cookie = null;
try {
ObjectInputStream ois = new ObjectInputStream(is);
cookie = ((SerializableCookie) ois.readObject()).getCookie();
} catch (Exception e) {
e.printStackTrace();
}
return cookie;
}
// Using some super basic byte array <-> hex conversions so we don't have
// to rely on any large Base64 libraries. Can be overridden if you like!
protected synchronized String byteArrayToHexString(byte[] b) {
StringBuffer sb = new StringBuffer(b.length * 2);
for (byte element : b) {
int v = element & 0xff;
if (v < 16) {
sb.append('0');
}
sb.append(Integer.toHexString(v));
}
return sb.toString().toUpperCase();
}
protected synchronized byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character
.digit(s.charAt(i + 1), 16));
}
return data;
}
}
Do something like this:
httpClient.setCookieStoreage(new PersistentCookieStore(this)) in your application subclass where you init the httpclient
You are probably seeing a nasty, long-standing Android bug that causes the symptoms you are describing. Have a look at my answer here: https://stackoverflow.com/a/16447508/769265
You probably have to add following code inside the onCreate() event of launcher Activity.
if (!isTaskRoot()) {
final Intent intent = getIntent();
final String action = intent.getAction();
if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) && action != null && action.equals(Intent.ACTION_MAIN)) {
finish();//Launcher Activity is not the root. So,finish it instead of launching
return;
}
}
android:launchMode="singleInstance"
android:alwaysRetainTaskState="true"
Try adding this two attributes to your Activity in manifest, this will make sure newIntent is called when activity is resumed from background.
I want to read and react to logcat logs within my application.
I found the following code:
try {
Process process = Runtime.getRuntime().exec("logcat -d");
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
StringBuilder log=new StringBuilder();
String line = "";
while ((line = bufferedReader.readLine()) != null) {
log.append(line);
}
TextView tv = (TextView)findViewById(R.id.textView1);
tv.setText(log.toString());
}
catch (IOException e) {}
This code indeed returns the logcat logs that made until the application was started -
But is it possible to continuously listen to even new logcat logs?
You can keep reading the logs, just by removing the "-d" flag in your code above.
The "-d" flag instruct to logcat to show log content and exit. If you remove the flag, logcat will not terminate and keeps sending any new line added to it.
Just have in mind that this may block your application if not correctly designed.
good luck.
With coroutines and the official lifecycle-livedata-ktx and lifecycle-viewmodel-ktx libraries it's simple like that:
class LogCatViewModel : ViewModel() {
fun logCatOutput() = liveData(viewModelScope.coroutineContext + Dispatchers.IO) {
Runtime.getRuntime().exec("logcat -c")
Runtime.getRuntime().exec("logcat")
.inputStream
.bufferedReader()
.useLines { lines -> lines.forEach { line -> emit(line) }
}
}
}
Usage
val logCatViewModel by viewModels<LogCatViewModel>()
logCatViewModel.logCatOutput().observe(this, Observer{ logMessage ->
logMessageTextView.append("$logMessage\n")
})
You can clear your logcat with this method i'm using to clear after writing logcat to a file to avoid duplicated lines:
public void clearLog(){
try {
Process process = new ProcessBuilder()
.command("logcat", "-c")
.redirectErrorStream(true)
.start();
} catch (IOException e) {
}
}
Here is a quick put-together/drop-in that can be used for capturing all current, or all new (since a last request) log items.
You should modify/extend this, because you might want to return a continuous-stream rather than a LogCapture.
The Android LogCat "Manual": https://developer.android.com/studio/command-line/logcat.html
import android.util.Log;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Stack;
/**
* Created by triston on 6/30/17.
*/
public class Logger {
// http://www.java2s.com/Tutorial/Java/0040__Data-Type/SimpleDateFormat.htm
private static final String ANDROID_LOG_TIME_FORMAT = "MM-dd kk:mm:ss.SSS";
private static SimpleDateFormat logCatDate = new SimpleDateFormat(ANDROID_LOG_TIME_FORMAT);
public static String lineEnding = "\n";
private final String logKey;
private static List<String> logKeys = new ArrayList<String>();
Logger(String tag) {
logKey = tag;
if (! logKeys.contains(tag)) logKeys.add(logKey);
}
public static class LogCapture {
private String lastLogTime = null;
public final String buffer;
public final List<String> log, keys;
LogCapture(String oLogBuffer, List<String>oLogKeys) {
this.buffer = oLogBuffer;
this.keys = oLogKeys;
this.log = new ArrayList<>();
}
private void close() {
if (isEmpty()) return;
String[] out = log.get(log.size() - 1).split(" ");
lastLogTime = (out[0]+" "+out[1]);
}
private boolean isEmpty() {
return log.size() == 0;
}
public LogCapture getNextCapture() {
LogCapture capture = getLogCat(buffer, lastLogTime, keys);
if (capture == null || capture.isEmpty()) return null;
return capture;
}
public String toString() {
StringBuilder output = new StringBuilder();
for (String data : log) {
output.append(data+lineEnding);
}
return output.toString();
}
}
/**
* Get a list of the known log keys
* #return copy only
*/
public static List<String> getLogKeys() {
return logKeys.subList(0, logKeys.size() - 1);
}
/**
* Platform: Android
* Get the logcat output in time format from a buffer for this set of static logKeys.
* #param oLogBuffer logcat buffer ring
* #return A log capture which can be used to make further captures.
*/
public static LogCapture getLogCat(String oLogBuffer) { return getLogCat(oLogBuffer, null, getLogKeys()); }
/**
* Platform: Android
* Get the logcat output in time format from a buffer for a set of log-keys; since a specified time.
* #param oLogBuffer logcat buffer ring
* #param oLogTime time at which to start capturing log data, or null for all data
* #param oLogKeys logcat tags to capture
* #return A log capture; which can be used to make further captures.
*/
public static LogCapture getLogCat(String oLogBuffer, String oLogTime, List<String> oLogKeys) {
try {
List<String>sCommand = new ArrayList<String>();
sCommand.add("logcat");
sCommand.add("-bmain");
sCommand.add("-vtime");
sCommand.add("-s");
sCommand.add("-d");
sCommand.add("-T"+oLogTime);
for (String item : oLogKeys) sCommand.add(item+":V"); // log level: ALL
sCommand.add("*:S"); // ignore logs which are not selected
Process process = new ProcessBuilder().command(sCommand).start();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
LogCapture mLogCapture = new LogCapture(oLogBuffer, oLogKeys);
String line = "";
long lLogTime = logCatDate.parse(oLogTime).getTime();
if (lLogTime > 0) {
// Synchronize with "NO YEAR CLOCK" # unix epoch-year: 1970
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date(oLogTime));
calendar.set(Calendar.YEAR, 1970);
Date calDate = calendar.getTime();
lLogTime = calDate.getTime();
}
while ((line = bufferedReader.readLine()) != null) {
long when = logCatDate.parse(line).getTime();
if (when > lLogTime) {
mLogCapture.log.add(line);
break; // stop checking for date matching
}
}
// continue collecting
while ((line = bufferedReader.readLine()) != null) mLogCapture.log.add(line);
mLogCapture.close();
return mLogCapture;
} catch (Exception e) {
// since this is a log reader, there is nowhere to go and nothing useful to do
return null;
}
}
/**
* "Error"
* #param e
*/
public void failure(Exception e) {
Log.e(logKey, Log.getStackTraceString(e));
}
/**
* "Error"
* #param message
* #param e
*/
public void failure(String message, Exception e) {
Log.e(logKey, message, e);
}
public void warning(String message) {
Log.w(logKey, message);
}
public void warning(String message, Exception e) {
Log.w(logKey, message, e);
}
/**
* "Information"
* #param message
*/
public void message(String message) {
Log.i(logKey, message);
}
/**
* "Debug"
* #param message a Message
*/
public void examination(String message) {
Log.d(logKey, message);
}
/**
* "Debug"
* #param message a Message
* #param e An failure
*/
public void examination(String message, Exception e) {
Log.d(logKey, message, e);
}
}
In your project which performs activity logging:
Logger log = new Logger("SuperLog");
// perform logging methods
When you want to capture everything you logged through "Logger"
LogCapture capture = Logger.getLogCat("main");
When you get hungry and you want to snack on more logs
LogCapture nextCapture = capture.getNextCapture();
You can get the capture as a string with
String captureString = capture.toString();
Or you can get the log items of the capture with
String logItem = capture.log.get(itemNumber);
There is no exact static method to capture foreign log keys but there is a way none the less
LogCapture foreignCapture = Logger.getLogCat("main", null, foreignCaptureKeyList);
Using the above will also permit you to call Logger.this.nextCapture on the foreign capture.
Based on #user1185087's answer, a simple solution without ViewModel could be:
Start the job on an IO thread:
// Custom scope for collecting logs on IO threads.
val scope = CoroutineScope(Job() + Dispatchers.IO)
val job = scope.launch {
Runtime.getRuntime().exec("logcat -c") // Clear logs
Runtime.getRuntime().exec("logcat") // Start to capture new logs
.inputStream
.bufferedReader()
.useLines { lines ->
// Note that this forEach loop is an infinite loop until this job is cancelled.
lines.forEach { newLine ->
// Check whether this job is cancelled, since a coroutine must
// cooperate to be cancellable.
ensureActive()
// TODO: Write newLine into a file or buffer or anywhere appropriate
}
}
}
Cancel the job from the main thread:
MainScope().launch {
// Cancel the job and wait for its completion on main thread.
job.cancelAndJoin()
job = null // May be necessary
// TODO: Anything else you may want to clean up
}
This solution should suffice if you want to collect your app's new logs continuously on a background thread.
The "-c" flag clears the buffer.
-c Clears (flushes) the entire log and exits.
//CLEAR LOGS
Runtime.getRuntime().exec("logcat -c");
//LISTEN TO NEW LOGS
Process pq=Runtime.getRuntime().exec("logcat v main");
BufferedReader brq = new BufferedReader(new InputStreamReader(pq.getInputStream()));
String sq="";
while ((sq = brq.readLine()) != null)
{
//CHECK YOUR MSG HERE
if(sq.contains("send MMS with param"))
{
}
}
I am using this in my app and it works .
And you can use above code in Timer Task so that it wont stop your main thread
Timer t;
this.t.schedule(new TimerTask()
{
public void run()
{
try
{
ReadMessageResponse.this.startRecord();//ABOVE METHOD HERE
}
catch (IOException ex)
{
//NEED TO CHECK SOME VARIABLE TO STOP MONITORING LOGS
System.err.println("Record Stopped");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
ReadMessageResponse.this.t.cancel();
}
}
}, 0L);
}
Try to add this permission into the mainfest:
<uses-permission android:name="android.permission.READ_LOGS"/>
Goal
Collect periodic updates of the LogCat and save (append) those chunks of text to a file on the SDcard
Problem
The Log class doesn't provide updates since a specific time-stamp
Possible solution
My plan is to periodically run code that is similar to: http://www.helloandroid.com/tutorials/reading-logs-programatically
or https://stackoverflow.com/a/9039352/550471
However, with one notable difference: use the -v time parameter to ensure that each line is time-stamped.
After each time the LogCat data is collected, the app will store the time-stamp of the last Log entry. The next time the LogCat data is collected the app will search through the text to find the time-stamp and then save the chunk of data to sdcard that was added to the Log since the specified time-stamp.
Possible problem
If the LogCat data is collected at too short periods then the CPU is busy processing a lot of 'old' data.
If the Logcat data is collected at too long periods then some data could be missed.
Is there a better way ?
This is what I came up with - it works very well when it doesn't freeze up.
As you might know, Runtime.getRuntime().exec("") has a pretty good chance of causing an ANR in Android earlier than Jelly Bean. If someone has a solution to overcome the ANR, then please share.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import android.os.Environment;
import android.util.Log;
/*
* For (compressed) buffer sizes, see: http://elinux.org/Android_Logging_System
* buffer:main = 64KB
* buffer:radio = 64KB
* buffer:system = 64KB
* buffer:event = 256KB
*
* NOTE: the 'command' must include "-d -v time" !!
* to switch buffers, use "-b <buffer>"
*/
public class LogCatReader {
// constants
private static final String CR = "\r\n";
private static final String END_OF_DATE_TIME = "): ";
private static final int DEFAULT_SEARCH_START_INDEX = 0;
// member variables
private StringBuilder mLog;
private LogThread mLogThread = null;
private String mLastLogReadToken = "";
private String mLogCommand = "";
private int mStringCapacity;
private File mFileTarget = null;
// constructor
public LogCatReader(String command, int capacity) {
mLogCommand = command;
mStringCapacity = capacity;
}
// returns complete logcat buffer
// note: takes about 1.5sec to finish
synchronized public StringBuilder getLogComplete() {
try {
// capacity should be about 25% bigger than buffer size since the
// buffer is compressed
mLog = new StringBuilder(mStringCapacity);
// command to capture log
Process process = Runtime.getRuntime().exec(mLogCommand);
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
// append() is costly if capacity needs to be increased, be sure
// to reserve enough in the first place
mLog.append(line + CR);
}
} catch (IOException e) {
}
return mLog;
}
public String getLogUpdatesOnly() {
String strReturn = "";
StringBuilder sbLog = getLogComplete();
try {
int iStartindex = DEFAULT_SEARCH_START_INDEX;
// if there exists a token from a previous search then use that
if (mLastLogReadToken.length() > 0) {
iStartindex = sbLog.indexOf(mLastLogReadToken);
// if string not found then start at beginning
if (iStartindex == -1) {
// start search at beginning of log
iStartindex = DEFAULT_SEARCH_START_INDEX;
}
}
int iEndindex = sbLog.length();
// if token is found then move index to the next line
if (iStartindex > DEFAULT_SEARCH_START_INDEX) {
iStartindex = sbLog.indexOf(CR, iStartindex);
if (iStartindex != -1) {
iStartindex += CR.length();
} else {
// return an empty string
iStartindex = iEndindex;
}
}
// grab the data between the start and end indices
strReturn = sbLog.substring(iStartindex, iEndindex);
// grab date/time token for next search
iStartindex = sbLog.lastIndexOf(END_OF_DATE_TIME);
if (iStartindex != -1) {
iEndindex = iStartindex;
iStartindex = sbLog.lastIndexOf(CR, iEndindex);
iStartindex += CR.length();
if (iStartindex == -1) {
// read from beginning
iStartindex = 0;
}
mLastLogReadToken = sbLog.substring(iStartindex, iEndindex);
}
} catch (Exception e) {
strReturn = "";
}
return strReturn;
}
public void startPeriodicLogCatReader(int timePeriod, String logfilename) {
if (mLogThread == null) {
mLogThread = new LogThread(timePeriod, logfilename);
mLogThread.start();
}
}
public void stopPeriodicLogCatReader() {
if (mLogThread != null) {
mLogThread.interrupt();
mLogThread = null;
}
}
private class LogThread extends Thread {
private boolean mInterrupted;
private int mTimePeriod;// in seconds
private String mLogref;
private BufferedWriter mBuffWriter = null;
public boolean mPauseLogCollection = false;
// constructor: logfilename is optional - pass null to not use
public LogThread(int timePeriod, String logfilename) {
mTimePeriod = timePeriod;
if (logfilename != null) {
File fLogFolder = new File(
Environment.getExternalStorageDirectory() + "/logfiles");
if (fLogFolder.exists() == false) {
if (fLogFolder.mkdirs() == false) {
Log.e("LogCatReader",
"Could not create "
+ fLogFolder.getAbsolutePath());
}
}
mFileTarget = new File(
Environment.getExternalStorageDirectory() + "/logfiles",
logfilename);
if (mFileTarget.exists() == false) {
try {
// file doesn't yet exist - create a fresh one !
mFileTarget.createNewFile();
} catch (IOException e) {
e.printStackTrace();
mFileTarget = null;
}
}
}
}
#Override
public void interrupt() {
mInterrupted = true;
super.interrupt();
}
#Override
public void run() {
super.run();
// initialization
mInterrupted = false;
// set up storage
if (mFileTarget != null) {
try {
mBuffWriter = new BufferedWriter(new FileWriter(
mFileTarget, true), 10240);
} catch (IOException e) {
e.printStackTrace();
}
}
while ((mInterrupted == false) && (mBuffWriter != null)) {
if (mPauseLogCollection == false) {
// read log updates
mLogref = getLogUpdatesOnly();
// save log updates to file
try {
mBuffWriter.append(mLogref);
mBuffWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
if (!mInterrupted) {
try {
sleep(mTimePeriod * 1000);
} catch (InterruptedException e) {
}
}
}
if (mBuffWriter != null) {
try {
mBuffWriter.close();
mBuffWriter = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}// end of inner class
}// end of outer class
The procedure I used to find only the updates is to capture the date and time of the very last line of a logcat and use that as the search token next time around.
To use this class, the following is an example:
LogCatReader logcatPeriodicReader = new LogCatReader("logcat -b main -d -v time", 80 * 1024);//collect "main" buffer, exit after reading logcat
logcatPeriodicReader.startPeriodicLogReader(90, "log.txt");//read logcat every 90 secs
I would like to create a Jersey client in Android using protocol buffer.
I am using the following libraries:
jersey-client-1.8.jar
jersey-core-1.8.jar
protobuf-java-2.4.0a.jar
The code I have written:
import com.sun.jersey.api.client.ClientRequest;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.WebResource.Builder;
import com.sun.jersey.api.client.filter.ClientFilter;
import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
BaseRestClient client = BaseRestClient.create("", "");
HTTPBasicAuthFilter authenticationFilter =
new HTTPBasicAuthFilter(username, password);
client.addFilter(authenticationFilter);
..........
..........
WebResource webResourceGetMea = client.resource(url);
webResourceGetMea = webResourceGetMea.path("/accounts").path("/login");
ClientResponse responseGetMea = webResourceGetMea.type("application/x-protobuf").get(ClientResponse.class);
The above code is running successfully as Java main() application but when I am running it on Android the responseGetMea() object is null (last line of code).
I am using the "application/x-protobuf" because in such way it was defined on server side.
I have added the INTERNET permission in my Android application.
I also checked the URL from Android browser and when I click it, it prompts me to input the user name and the password(the expected behaviour).
I really appreciate any help.
Regards,
kalgik
An addition... When trying to POST with the version of Buscador at the previous link it complained with some errors. The new version of Buscador that works for POSTing is the following,
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import com.sun.jersey.spi.service.ServiceFinder;
import com.sun.jersey.spi.service.ServiceFinder.DefaultServiceIteratorProvider;
import com.sun.jersey.spi.service.ServiceFinder.ServiceIteratorProvider;
public class Buscador<T> extends ServiceIteratorProvider<T>
{
private static final HashMap<String, String[]> SERVICES = new HashMap<String, String[]>();
private static final String[] com_sun_jersey_spi_HeaderDelegateProvider = new String[] {
"com.sun.jersey.core.impl.provider.header.LocaleProvider",
"com.sun.jersey.core.impl.provider.header.EntityTagProvider",
"com.sun.jersey.core.impl.provider.header.MediaTypeProvider",
"com.sun.jersey.core.impl.provider.header.CacheControlProvider",
"com.sun.jersey.core.impl.provider.header.NewCookieProvider",
"com.sun.jersey.core.impl.provider.header.CookieProvider",
"com.sun.jersey.core.impl.provider.header.URIProvider",
"com.sun.jersey.core.impl.provider.header.DateProvider",
"com.sun.jersey.core.impl.provider.header.StringProvider"
};
private static final String[] com_sun_jersey_spi_inject_InjectableProvider = new String[] {
"com.sun.jersey.core.impl.provider.xml.SAXParserContextProvider",
"com.sun.jersey.core.impl.provider.xml.XMLStreamReaderContextProvider",
"com.sun.jersey.core.impl.provider.xml.DocumentBuilderFactoryProvider",
"com.sun.jersey.core.impl.provider.xml.TransformerFactoryProvider"
};
private static final String[] javax_ws_rs_ext_MessageBodyReader = new String[] {
"com.sun.jersey.core.impl.provider.entity.StringProvider",
"com.sun.jersey.core.impl.provider.entity.ByteArrayProvider",
"com.sun.jersey.core.impl.provider.entity.FileProvider",
"com.sun.jersey.core.impl.provider.entity.InputStreamProvider",
"com.sun.jersey.core.impl.provider.entity.DataSourceProvider",
"com.sun.jersey.core.impl.provider.entity.RenderedImageProvider",
"com.sun.jersey.core.impl.provider.entity.MimeMultipartProvider",
"com.sun.jersey.core.impl.provider.entity.FormProvider",
"com.sun.jersey.core.impl.provider.entity.FormMultivaluedMapProvider",
"com.sun.jersey.core.impl.provider.entity.XMLRootElementProvider$App",
"com.sun.jersey.core.impl.provider.entity.XMLRootElementProvider$Text",
"com.sun.jersey.core.impl.provider.entity.XMLRootElementProvider$General",
"com.sun.jersey.core.impl.provider.entity.XMLJAXBElementProvider$App",
"com.sun.jersey.core.impl.provider.entity.XMLJAXBElementProvider$Text",
"com.sun.jersey.core.impl.provider.entity.XMLJAXBElementProvider$General",
"com.sun.jersey.core.impl.provider.entity.XMLListElementProvider$App",
"com.sun.jersey.core.impl.provider.entity.XMLListElementProvider$Text",
"com.sun.jersey.core.impl.provider.entity.XMLListElementProvider$General",
"com.sun.jersey.core.impl.provider.entity.ReaderProvider",
"com.sun.jersey.core.impl.provider.entity.DocumentProvider",
"com.sun.jersey.core.impl.provider.entity.SourceProvider$StreamSourceReader",
"com.sun.jersey.core.impl.provider.entity.SourceProvider$SAXSourceReader",
"com.sun.jersey.core.impl.provider.entity.SourceProvider$DOMSourceReader",
"com.sun.jersey.core.impl.provider.entity.XMLRootObjectProvider$App",
"com.sun.jersey.core.impl.provider.entity.XMLRootObjectProvider$Text",
"com.sun.jersey.core.impl.provider.entity.XMLRootObjectProvider$General",
"com.sun.jersey.core.impl.provider.entity.EntityHolderReader"
};
private static final String[] javax_ws_rs_ext_MessageBodyWriter = new String[] {
"com.sun.jersey.core.impl.provider.entity.StringProvider",
"com.sun.jersey.core.impl.provider.entity.ByteArrayProvider",
"com.sun.jersey.core.impl.provider.entity.FileProvider",
"com.sun.jersey.core.impl.provider.entity.InputStreamProvider",
"com.sun.jersey.core.impl.provider.entity.DataSourceProvider",
"com.sun.jersey.core.impl.provider.entity.RenderedImageProvider",
"com.sun.jersey.core.impl.provider.entity.MimeMultipartProvider",
"com.sun.jersey.core.impl.provider.entity.FormProvider",
"com.sun.jersey.core.impl.provider.entity.FormMultivaluedMapProvider",
"com.sun.jersey.core.impl.provider.entity.XMLRootElementProvider$App",
"com.sun.jersey.core.impl.provider.entity.XMLRootElementProvider$Text",
"com.sun.jersey.core.impl.provider.entity.XMLRootElementProvider$General",
"com.sun.jersey.core.impl.provider.entity.XMLJAXBElementProvider$App",
"com.sun.jersey.core.impl.provider.entity.XMLJAXBElementProvider$Text",
"com.sun.jersey.core.impl.provider.entity.XMLJAXBElementProvider$General",
"com.sun.jersey.core.impl.provider.entity.XMLListElementProvider$App",
"com.sun.jersey.core.impl.provider.entity.XMLListElementProvider$Text",
"com.sun.jersey.core.impl.provider.entity.XMLListElementProvider$General",
"com.sun.jersey.core.impl.provider.entity.ReaderProvider",
"com.sun.jersey.core.impl.provider.entity.DocumentProvider",
"com.sun.jersey.core.impl.provider.entity.StreamingOutputProvider",
"com.sun.jersey.core.impl.provider.entity.SourceProvider$SourceWriter"
};
static
{
SERVICES.put("com.sun.jersey.spi.HeaderDelegateProvider",
com_sun_jersey_spi_HeaderDelegateProvider);
SERVICES.put("com.sun.jersey.spi.inject.InjectableProvider",
com_sun_jersey_spi_inject_InjectableProvider);
SERVICES.put("javax.ws.rs.ext.MessageBodyReader", javax_ws_rs_ext_MessageBodyReader);
SERVICES.put("javax.ws.rs.ext.MessageBodyWriter", javax_ws_rs_ext_MessageBodyWriter);
}
DefaultServiceIteratorProvider defaultServiceIteratorProvider = new ServiceFinder.DefaultServiceIteratorProvider();
#SuppressWarnings("unchecked")
#Override
public Iterator<Class<T>> createClassIterator(Class<T> service, String serviceName,
ClassLoader loader, boolean ignoreOnClassNotFound)
{
String[] classesNames = SERVICES.get(serviceName);
System.out.println("!!!!!!!!!!!! serviceName: " + serviceName + " !!!!!!!!!!!!!!!!!!!");
if(classesNames==null)
{
return defaultServiceIteratorProvider.createClassIterator(service, serviceName, loader, ignoreOnClassNotFound);
}
int length = classesNames.length;
ArrayList<Class<T>> classes = new ArrayList<Class<T>>(length);
for (int i = 0; i < length; i++)
{
try
{
classes.add((Class<T>) Class.forName(classesNames[i]));
} catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
//return null;
return classes.iterator();
}
#Override
public Iterator<T> createIterator(Class<T> service, String serviceName, ClassLoader loader,
boolean ignoreOnClassNotFound)
{
String[] classesNames = SERVICES.get(serviceName);
int length = classesNames.length;
ArrayList<T> classes = new ArrayList<T>(length);
for (int i = 0; i < length; i++)
{
try
{
classes.add(service.cast(Class.forName(classesNames[i]).newInstance()));
} catch (IllegalAccessException e)
{
e.printStackTrace();
} catch (InstantiationException e)
{
e.printStackTrace();
} catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
return classes.iterator();
}
}
I employed the solution offered at,
java.lang.NullPointerException on Android
as proposed by
Lucas Ventura, Aug 25, 2010; 9:15am
and it worked like a charm.
[EDIT]
Well, small comment/correction. Running in an HTC phone, caused the app to destroy/create when i minimised (not sure if this is normal) and re-opened. The solution proposed mandates that the Jersey client object and the ServiceFinder setting should occur in a static context. This should give a clue,
private static final BaseRestClient client;
static {
client = BaseRestClient.create("", ""); // just a helper class
ServiceFinder.setIteratorProvider(new Buscador());
}
Otherwise, the class loading fix complains in a rather strange way. Hope this helps someone...
Cheers!