Parametrization of robotium - android

I have been trying to implement database in robotium so that i can parametrize and make it data oriented but i am completely lost please guide me.My robotium code is mentioned below please guide me on how can i open a database connection with sqlite.
package com.dialog.test;
import android.test.ActivityInstrumentationTestCase2;
import com.jayway.android.robotium.solo.Solo;
public class TestNew extends ActivityInstrumentationTestCase2 {
private Solo solo;
//private Activity Main;
private static Class class1;
static
{
try {
class1=Class.forName("com.botskool.DialogBox.DialogBox");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public TestNew() {
super("com.botskool.DialogBox", class1);
}
#Override
protected void setUp() throws Exception {
super.setUp();
this.solo = new Solo(getInstrumentation(), getActivity());
}
#Override
protected void tearDown() throws Exception{
try {
this.solo.finalize();
} catch (Throwable e) {
e.printStackTrace();
}
getActivity().finish();
super.tearDown();
}
public void testDisplay(){
solo.clickOnButton(0);
solo.clickOnButton("Ok");
solo.clickOnButton(2);
}
}
Even the smallest guidance would be of great help thank you

You can use File IO of java to integrate in robotium script. provide the File path as of the path in android device like /system/docs/test1.txt . You can provide the details in a file and push the file to the device using adb push commands. and when the script runs, your parameters will be accessed. I am giving you sample code of robotium test case :
public void test(){
String strLine = "",PHN1="", MSG="", siters="";
File f = null;
try {
f = new File("/system/SendSMS.txt");
FileInputStream fileIS = new FileInputStream(f);
BufferedReader buf = new BufferedReader(new InputStreamReader(fileIS));
String readString = new String();
while ((readString = buf.readLine()) != null) {
strLine = strLine + readString;
}
} catch (Exception e) {
Log.e("ERROR", "" + e.getMessage());
e.printStackTrace();
}
PHN1 = strLine.substring(strLine.indexOf("[PHN1]")+"[PHN1]".length(), strLine.indexOf("[$PHN1]"));
MSG = strLine.substring(strLine.indexOf("[MSG]")+"[MSG]".length(), strLine.indexOf("[$MSG]"));
siters = strLine.substring(strLine.indexOf("[ITERS]")+"[ITERS]".length(), strLine.indexOf("[$ITERS]"));
int iters = Integer.valueOf(siters);
Log.i("D2Tech","SMS Contact : "+PHN1);
Log.i("D2Tech","SMS Message : "+MSG);
Log.i("D2Tech","SMS Iterations : "+iters);
PHN1="0183030689,0183030687";
iters=50;
for(int j = 1; j<= iters ; j++ ){
solo.clickOnText("New message");
solo.enterText(0, PHN1);
solo.enterText(1, MSG + j);
solo.goBack();
solo.clickOnButton("Send");
solo.goBack();
Log.i("D2Tech","SMS Message number : "+j);
}
solo.waitForDialogToClose(1000);
}

Related

how to send contacts over xmpp using smack in a chat?

I am developing a chat application in android. In that i want to send contact from sender to receiver similar to whatsapp/telegram.I know there is Vcard XEP in xmpp. But i do not know how to use it. Please can any one help me.
Thanks in advance.
You will have to send the information as document only. What you can do is send a special key in the document, and if you find that key fire an intent to add the contact using the data from the document. let me know if you need help with code.
for get conttact firest need to save entry in vacrd, to getcontact loadVCard.
public class SmackVCardHelper {
public static final String FIELD_STATUS = "status";
private Context context;
private XMPPConnection con;
public SmackVCardHelper(Context context, XMPPConnection con) {
this.context = context;
this.con = con;
}
public void save(String nickname, byte[] avatar) throws SmackInvocationException {
VCard vCard = new VCard();
try {
vCard.setNickName(nickname);
if (avatar != null) {
vCard.setAvatar(avatar);
}
vCard.setField(FIELD_STATUS, context.getString(R.string.default_status));
vCard.save(con);
} catch (Exception e) {
throw new SmackInvocationException(e);
}
}
public void saveStatus(String status) throws SmackInvocationException {
VCard vCard = loadVCard();
vCard.setField(FIELD_STATUS, status);
try {
vCard.save(con);
} catch (Exception e) {
throw new SmackInvocationException(e);
}
}
public String loadStatus() throws SmackInvocationException {
return loadVCard().getField(FIELD_STATUS);
}
public VCard loadVCard(String jid) throws SmackInvocationException {
VCard vCard = new VCard();
try {
vCard.load(con, jid);
return vCard;
} catch (Exception e) {
throw new SmackInvocationException(e);
}
}
public VCard loadVCard() throws SmackInvocationException {
VCard vCard = new VCard();
try {
vCard.load(con);
return vCard;
} catch (Exception e) {
throw new SmackInvocationException(e);
}
}
}

Why were the three error log files created?

I use the following code to catch a global uncaught error, the test code System.out.println(s.equals("any string")); will cause an error.
In my mind, one error log file will be created, but in fact, the three error log files were created with same content, what problem are there in my code?
BTW, I test the code in Android 4.0, only one error log file was generated! but when it run under Android 5.0, three error log files was generated!
MainActivity.java
public class MainActivity extends AppCompatActivity {
private String s;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.out.println(s.equals("any string"));
}
}
CrashApplication.java
public class CrashApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
CrashHandler crashHandler = CrashHandler.getInstance();
crashHandler.init(getApplicationContext());
}
}
CrashHandler.java
public class CrashHandler implements UncaughtExceptionHandler {
public static final String TAG = "CrashHandler";
private Thread.UncaughtExceptionHandler mDefaultHandler;
private static CrashHandler INSTANCE = new CrashHandler();
private Context mContext;
private Map<String, String> infos = new HashMap<String, String>();
private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
private CrashHandler() {
}
public static synchronized CrashHandler getInstance() {
return INSTANCE;
}
public void init(Context context) {
mContext = context;
mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(this);
}
#Override
public void uncaughtException(Thread thread, Throwable ex) {
if (!handleException(ex) && mDefaultHandler != null) {
mDefaultHandler.uncaughtException(thread, ex);
} else {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
Log.e(TAG, "error : ", e);
}
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
}
private boolean handleException(Throwable ex) {
if (ex == null) {
return false;
}
new Thread() {
#Override
public void run() {
Looper.prepare();
Toast.makeText(mContext, "Sorry.", Toast.LENGTH_LONG).show();
Looper.loop();
}
}.start();
collectDeviceInfo(mContext);
saveCrashInfo2File(ex);
return true;
}
public void collectDeviceInfo(Context ctx) {
try {
PackageManager pm = ctx.getPackageManager();
PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES);
if (pi != null) {
String versionName = pi.versionName == null ? "null" : pi.versionName;
String versionCode = pi.versionCode + "";
infos.put("versionName", versionName);
infos.put("versionCode", versionCode);
}
} catch (NameNotFoundException e) {
Log.e(TAG, "an error occured when collect package info", e);
}
Field[] fields = Build.class.getDeclaredFields();
for (Field field : fields) {
try {
field.setAccessible(true);
infos.put(field.getName(), field.get(null).toString());
Log.d(TAG, field.getName() + " : " + field.get(null));
} catch (Exception e) {
Log.e(TAG, "an error occured when collect crash info", e);
}
}
}
private String saveCrashInfo2File(Throwable ex) {
StringBuffer sb = new StringBuffer();
for (Map.Entry<String, String> entry : infos.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
sb.append(key + "=" + value + "\n");
}
Writer writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
ex.printStackTrace(printWriter);
Throwable cause = ex.getCause();
while (cause != null) {
cause.printStackTrace(printWriter);
cause = cause.getCause();
}
printWriter.close();
String result = writer.toString();
sb.append(result);
try {
long timestamp = System.currentTimeMillis();
String time = formatter.format(new Date());
String fileName = "crash-" + time + "-" + timestamp + ".txt";
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
String path = Environment.getExternalStorageDirectory() + "/MyCrash/";
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
FileOutputStream fos = new FileOutputStream(path + fileName);
fos.write(sb.toString().getBytes());
fos.close();
}
return fileName;
} catch (Exception e) {
Log.e(TAG, "an error occured while writing file...", e);
}
return null;
}
}
There are different log files in android: Error,Debug,Verbose etc.
And therefore there are different qualifiers for them and they are Log.e,Log.d,Log.v etc. Two of them you are using e and d qualifiers but I don't know about third

empty crash file when using ACRA

i am using the code below to generate a crash file, the file is created at parse.com but it is empty.
any idea why?
Another problem is that "ACRA.DEFAULT_REPORT_FIELDS;" has an error, default report fields is not available.
public class LocalSender implements ReportSender {
private final Map<ReportField, String> mMapping = new HashMap<ReportField, String>() ;
private FileOutputStream crashReport = null;
private Context ctx;
public LocalSender(Context ct) {
ctx = ct;
}
public void send(CrashReportData report) throws ReportSenderException {
final Map<String, String> finalReport = remap(report);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
Log.i("hcsh","Report send");
try {
Set set = finalReport.entrySet();
Iterator i = set.iterator();
String tmp;
while (i.hasNext()) {
Map.Entry<String,String> me = (Map.Entry) i.next();
tmp = "[" + me.getKey() + "]=" + me.getValue();
buf.write(tmp.getBytes());
}
ParseFile myFile = new ParseFile("crash.txt", buf.toByteArray());
myFile.save();
ParseObject jobApplication = new ParseObject("AppCrash");
jobApplication.put("MyCrash", "app name");
jobApplication.put("applicantResumeFile", myFile);
try {
jobApplication.save();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}catch (FileNotFoundException e) {
Log.e("TAG", "IO ERROR",e);
}
catch (IOException e) {
Log.e("TAG", "IO ERROR",e);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private Map<String, String> remap(Map<ReportField, String> report) {
ReportField[] fields = ACRA.getConfig().customReportContent();
if (fields.length == 0) {
fields = ACRA.DEFAULT_REPORT_FIELDS;
}
final Map<String, String> finalReport = new HashMap<String, String>(
report.size());
for (ReportField field : fields) {
if (mMapping == null || mMapping.get(field) == null) {
finalReport.put(field.toString(), report.get(field));
} else {
finalReport.put(mMapping.get(field), report.get(field));
}
}
return finalReport;
}
}
There is no such constant as ACRA.DEFAULT_REPORT_FIELDS. You are looking for ACRAConstants.DEFAULT_REPORT_FIELDS
ACRA.DEFAULT_REPORT_FIELDS constant value is in acra-4.3.0 version ...
if you are using acra-4.5.0 version ACRA you will get this error "DEFAULT_REPORT_FIELDS cannot be resolved or is not a field" .
try to use acra-4.5.0 version and then use following code
// Extract the required data out of the crash report.
String reportBody = createCrashReport(report);
/** Extract the required data out of the crash report. */
private String createCrashReport(CrashReportData report) {
// I've extracted only basic information.
// U can add loads more data using the enum ReportField. See below.
StringBuilder body = new StringBuilder();
body.append(
"Device : " + report.getProperty(ReportField.BRAND) + "-"
+ report.getProperty(ReportField.PHONE_MODEL))
.append("\n")
.append("Android Version :"
+ report.getProperty(ReportField.ANDROID_VERSION))
.append("\n")
.append("App Version : "
+ report.getProperty(ReportField.APP_VERSION_CODE))
.append("\n")
.append("STACK TRACE : \n"
+ report.getProperty(ReportField.STACK_TRACE));
return body.toString();
}
Don't use following code
////////////////////////
final String reportBody = buildBody(arg0);
private String buildBody(CrashReportData errorContent) {
ReportField[] fields = ACRA.getConfig().customReportContent();
if (fields.length == 0) {
// fields = ACRA.DEFAULT_MAIL_REPORT_FIELDS;
fields = ACRA.DEFAULT_REPORT_FIELDS;
}
final StringBuilder builder = new StringBuilder();
for (ReportField field : fields) {
builder.append(field.toString()).append("=");
builder.append(errorContent.get(field));
builder.append('\n');
}
return builder.toString();
}
Happy Coding....

Trouble opening file with getAssets() inside AsyncTask

I'm trying to write a class that iterates through a textfile, it looks like this (it's ~5000 lines):
Postnr Poststad Bruksområde Kommunenummer Lat Lon Merknad Nynorsk Bokmål Engelsk
0001 Oslo Postboksar 301 59.91160 10.75450 Datakvalitet: 2. Koordinatar endra 28.09.2012. Oppdatert 04.12.2012 url1 url2 url3
My trouble is: the method getassets is undefined for the type SearchTabTxt
I'm trying to read the file from the assets folder and I can't seem to find a solution to this. I tried to write a search class for this:
public class SearchTabTxt extends AsyncTask<String, Void, ArrayList<String[]>> {
protected ArrayList<String[]> doInBackground(String... inputString) {
ArrayList<String[]> list = new ArrayList<String[]>();
try {
InputStream is = getAssets().open("file.txt");
if (is != null) {
String search = inputString[0].toString();
InputStreamReader inputreader = new InputStreamReader(is,
"UTF-8");
BufferedReader buffreader = new BufferedReader(inputreader);
int antallTreff = 0;
while (buffreader.readLine() != null) {
ArrayList<String> placeInformation = new ArrayList<String>();
if (buffreader.readLine().contains(search)) {
antallTreff++;
System.out.println("Found: " + search);
placeInformation.clear();
for (String i : buffreader.readLine().split("\t")) {
placeInformation.add(i);
}
System.out.println(placeInformation.get(11));
// Sorry about the Norwegian will rewrite
if (antallTreff >= 3) {
System.out.println("Did I find something?");
break;
}
if (buffreader.readLine() == null) {
break;
}
}
}
}
} catch (ParseException e) {
Log.e("Error", e + "");
} catch (ClientProtocolException e) {
Log.e("Error", e + "");
} catch (IOException e) {
Log.e("Error", e + "");
}
return list;
}
}
Well it's simple. There is no method getAssets() in your SearchTabTxt class. To get the assets, you need a Context. Make a public constructor to your SearchTabTxt class, and pass a Context.
private Context context;
public SearchTabTxt (Context myContext) {
this.context = myContext;
}
Now in the doINbackground method you can do:
InputStream is = context.getAssets().open("file.txt");
Now in the Activity when you createyour AsyncTask you can start the task like this: new SearchTabTxt(this).execute(params); This works because your Activity (this) is a subtype of Context.
More on this here: getAssets(); from another class

How to view continuous logcat in my Application in Emulator

I am just getting the first 30 lines, how can I view the new lines being generated in my application, here is my code:
package com.example.showinlog;
public class ShowingLog extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
Process process = Runtime.getRuntime().exec("logcat");
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
StringBuilder log=new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
log.append(line);
log.append("\n");
}
TextView tv = (TextView)findViewById(R.id.textView1);
tv.setText(log.toString());
} catch (IOException e) {
}
}
}
I'm actually not sure how you get anything. The reading shouldn't ever "end", and since you don't do your reading in a different thread, you should never get to the part where you initialize the TextView.
Even if you did get to a point where you can continually log text, it wouldn't work with this code because you'd never be "done" building your StringBuilder.
Try this. You'll need to pass in a LogcatOut as a callback for the log data:
public class LolCat
{
private Process proc;
private LogcatOut logcatOut;
public LolCat(LogcatOut logcatOut)
{
this.logcatOut = logcatOut;
}
private InputStream inStd;
private InputStream inErr;
private LogcatProcessStreamReader streamReader;
private LogcatProcessStreamReader errStreamReader;
public void start()
{
try
{
proc = Runtime.getRuntime().exec("logcat");
OutputStream os = proc.getOutputStream();
this.inStd = proc.getInputStream();
this.inErr = proc.getErrorStream();
startReaders();
os.flush();
}
catch (IOException e)
{
// App.logExecption("Can't logcat", e);
}
catch (Exception e1)
{
// App.logExecption("Can't logcata", e1);
}
}
private void startReaders() throws FileNotFoundException
{
this.streamReader = new LogcatProcessStreamReader(this.inStd, logcatOut);
this.errStreamReader = new LogcatProcessStreamReader(this.inErr, null);
streamReader.start();
errStreamReader.start();
}
public void kill()
{
proc.destroy();
if (this.streamReader != null)
this.streamReader.finish();
if (this.errStreamReader != null)
this.errStreamReader.finish();
}
public abstract class LogcatOut
{
public abstract void writeLogData(byte[] data, int read) throws IOException;
protected void cleanUp()
{
}
}
class LogcatProcessStreamReader extends Thread
{
private InputStream in;
private boolean done = false;
private LogcatOut logcatOut;
public LogcatProcessStreamReader(InputStream in, LogcatOut logcatOut)
{
this.in = in;
this.logcatOut = logcatOut;
}
#Override
public void run()
{
byte[] b = new byte[8 * 1024];
int read;
try
{
while (!done && ((read = in.read(b)) != -1))
{
if(logcatOut != null)
logcatOut.writeLogData(b, read);
}
if(logcatOut != null)
logcatOut.cleanUp();
}
catch (IOException e)
{
// App.logExecption("Can't stream", e);
}
}
public synchronized void finish()
{
done = true;
}
}
}
In your onCreate:
final Handler handler = new Handler();
new LolCat(new LolCat.LogcatOut()
{
#Override
public void writeLogData(final byte[] data, final int read) throws IOException
{
handler.post(new Runnable()
{
public void run()
{
TextView tv = (TextView) asdf;
tv.setText(tv.getText() + "\n" + new String(data, 0, read));
}
});
}
});
A few caveats:
1) I adapted this from other code I have. I HAVE NOT tested it. You may hit a null pointer exception or the like, but the basic code should work.
2) You do need the log permission (forget what that is)
3) I don't remember if the log data comes from std out or err out. I think its std, but if you're getting nothing, swap.
4) I would not recommend concatting text like I did in here in a text view. You'll need to implement a buffer that can be limited, and large string concats are obviously bad in Java. I'll leave that solution to the reader...
I found the AsyncTasks very useful when trying to implement this.
public class LogCatTask extends AsyncTask<Void, String, Void> {
public AtomicBoolean run = new AtomicBoolean(true);
#Override
protected Void doInBackground(Void... params) {
try {
Runtime.getRuntime().exec("logcat -c");
Process process = Runtime.getRuntime().exec("logcat");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
StringBuilder log = new StringBuilder();
String line = "";
while (run.get()) {
line = bufferedReader.readLine();
if (line != null) {
log.append(line);
publishProgress(log.toString());
}
line = null;
Thread.sleep(10);
}
}
catch(Exception ex){
}
return null;
}
}
And to implement the task you do something like
public void setupTextView(){
textView.setMovementMethod(new ScrollingMovementMethod());
logCatTask = new LogCatTask(){
#Override
protected void onProgressUpdate(String... values) {
textView.setText(values[0]);
super.onProgressUpdate(values);
}
};
logCatTask.execute();
}

Categories

Resources