Is it possible to generate a main.xml inside onCreate()? Such as:
package avm.project;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.lang.reflect.Field;
import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ViewFlipper;
public class AVMOrderSystemActivity extends Activity {
ViewFlipper flipper;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
//File[] listOfFiles = folder.listFiles();
/*for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
Log.i("XML Generator","File " + listOfFiles[i].getName());
} else if (listOfFiles[i].isDirectory()) {
Log.i("XML Generator","Directory " + listOfFiles[i].getName());
}
}*/
String xml="";
xml=xml+"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
xml=xml+"<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n"+
"android:layout_width=\"fill_parent\" android:layout_height=\"wrap_content\"\n"+
"android:orientation=\"horizontal\" android:padding= \"5px\">\n";
xml=xml+"<ViewFlipper android:id=\"#+id/adflipper\"\n"+
"android:inAnimation=\"#android:anim/fade_in\" android:outAnimation=\"#android:anim/slide_out_right\"\n"+
"android:paddingLeft=\"15px\" android:layout_width=\"fill_parent\"\n"+
"android:layout_height=\"fill_parent\" android:autoStart=\"true\"\n"+
"android:flipInterval=\"5000\">";
Resources a=this.getResources();
try
{
for (int i=0x7f020000 ;i<0x7f020020;i++)
{
String name=a.getResourceName(i);
xml=xml+"<ImageView android:layout_width=\"fill_parent\" android:src=\"#"+name.substring(name.indexOf(':')+1)+"\"\n"+
"android:layout_height=\"fill_parent\"></ImageView>\n";
}
}
catch(Exception e)
{
Log.i("resoruces","exception");
e.printStackTrace();
}
xml=xml+"</ViewFlipper>\n</RelativeLayout>";
xml=xml+"<!--xxx-->";
try{
// Create file
FileWriter fstream = new FileWriter("res/layout/main.xml");
BufferedWriter out = new BufferedWriter(fstream);
out.write(xml);
//Close the output stream
out.close();
}catch (Exception e){//Catch exception if any
Log.i("xml write","exception");
e.printStackTrace();
}
setContentView(R.layout.main);
flipper=(ViewFlipper)findViewById(R.id.adflipper);
Button btn=(Button)findViewById(R.id.restbutton);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
flipper.showNext();
}
});
}
}
I have implemented the code and it can get the project drawables to generate a main.xml accordingly but its not working (I got an exception: file not found res/layout/main.xml). (My aim is to generate main.xml according to varying number of png images) What am I doing wrong, Is it possible to get over this or Is there any other solution?
Thanks.
You can change the src of your ImageView dynamically without having to generate the XML.
ImageView imageView = (ImageView) findViewById(R.id.your_image_view);
imageView.setImageDrawable(getResources().getDrawable(R.drawable.your_png));
And you can add more by creating them dynamically and adding them to the parent RelativeLayout:
for (int i=0x7f020000 ;i<0x7f020020;i++)
ImageView imageView = new ImageView(this);
imageview.setBackgroundResource(R.drawable.your_png_reference);
RelativeLayout ll = (RelativeLayout) findViewById(R.id.your_relative_layout_id);
ll.addView(imageView);
}
Related
I'm trying to get the rotation information in the MP4 video, I'm trying to use mp4parser for this but I'm not sure how can I get it, I'm doing this,
IsoFile isoFile = null;
try {
isoFile = new IsoFile(filePath);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
List<Box> boxes = isoFile.getBoxes();
for (Box box : boxes) {
System.out.println(box);
}
and the output is this
I/System.out(23548): FileTypeBox[majorBrand=isom;minorVersion=0;compatibleBrand=isom;compatibleBrand=3gp4]
I/System.out(23548): MovieBox[]
I/System.out(23548): com.coremedia.iso.boxes.FreeBox#0
I/System.out(23548): MediaDataBox{size=7913167}
Any idea how can I get the rotation tag value?
Update 1 The working code
import java.io.File;
import java.io.FileInputStream;
import android.app.Activity;
import android.os.Bundle;
import com.coremedia.iso.IsoFile;
import com.coremedia.iso.IsoTypeReader;
import com.coremedia.iso.boxes.Box;
import com.coremedia.iso.boxes.MovieBox;
import com.coremedia.iso.boxes.UserDataBox;
import com.googlecode.mp4parser.authoring.Movie;
import com.googlecode.mp4parser.authoring.container.mp4.MovieCreator;
import com.googlecode.mp4parser.util.Matrix;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String filePath = "/storage/emulated/0/test/test.mp4";
Activity activity = (Activity) MainActivity.this;
movie = MovieCreator.build(filePath);
Matrix matrix = movie.getMatrix();
}
}
You need to get Movie object from the IsoFile or read it with MovieCreator.build(), then with movie.getMatrix() obtain what is the type of matrix: Matrix.ROTATE_O, Matrix.ROTATE_90, Matrix.ROTATE_180, Matrix.ROTATE_270
String filePath = "/path/to/movie/file.mp4"
Movie movie = MovieCreator.build(new FileInputStream(new File(filePath)).getChannel());
Matrix matrix = movie.getMatrix();
The problem I am having is that I am trying to parse this website but I am getting thiserror . I am new to Jsoup and not quite sure whats making the error. Is there a way to stop parsing on certain element like if i want it to stop on first instance of Bobby? (row : Cindy : Mike : Bobby). Thanks in advance!
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.os.StrictMode.ThreadPolicy;
import org.jsoup.Jsoup;
import java.io.IOException;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class tableScreen extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.table);
takeTable();
}
public static int SDK_INT = android.os.Build.VERSION.SDK_INT;
public void takeTable()
{
Document doc = null;
if (SDK_INT >= 10)
{
ThreadPolicy tp = ThreadPolicy.LAX;
StrictMode.setThreadPolicy(tp);
}
try{
doc = Jsoup.connect("http://www.htmlgoodies.com/tutorials/tables/article.php/3479851").get();
System.out.println("1");
Element containingDiv = doc.select(".body").first();
System.out.println("2");
Elements table = containingDiv.select("table");
System.out.println("3");
Elements rows = table.select("tr");
System.out.println("4");
for (Element row : rows)
{
System.out.println("row: "+row.child(0).text()+" : "+row.child(1).text()+" : "+ row.child(2).text());
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
OK guys I manage to fix it ,
doc = Jsoup.connect("http://www.htmlgoodies.com/tutorials/tables/article.php/3479851").get();
Element containingDiv = doc.select("table").first();
Elements table = containingDiv.select("tbody");
Elements rows = table.select("tr");
I'm parsing XML from URL. What changes has been made to parse same XML file from raw folder. Have any idea to how to reduce code ?
This my xml file :umesh.xml
<?xml version="1.0" encoding="utf-8"?>
<appdata>
<brand name="Lovely Products">
<product>Hat</product>
<product>Gloves</product>
</brand>
<brand name="Great Things">
<product>Table</product>
<product>Chair</product>
<product>Bed</product>
</brand>
</appdata>
Below is my java file :
DataHandler.java
package com.umesh.xmlparsing;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import android.content.Context;
import android.content.res.XmlResourceParser;
import android.graphics.Color;
import android.util.Log;
import android.widget.TextView;
public class DataHandler extends DefaultHandler{
//list for imported product data
private ArrayList<TextView> theViews;
//string to track each entry
private String currBrand = "";
//flag to keep track of XML processing
private boolean isProduct = false;
//context for user interface
private Context theContext;
//constructor
public DataHandler(Context cont) {
super();
theViews = new ArrayList<TextView>();
theContext = cont;
}
//start of the XML document
public void startDocument () { Log.i("DataHandler", "Start of XML document"); }
//end of the XML document
public void endDocument () { Log.i("DataHandler", "End of XML document"); }
//opening element tag
public void startElement (String uri, String name, String qName, Attributes atts)
{
//handle the start of an element
//find out if the element is a brand
if(qName.equals("brand"))
{
//set product tag to false
isProduct = false;
//create View item for brand display
TextView brandView = new TextView(theContext);
brandView.setTextColor(Color.rgb(73, 136, 83));
//add the attribute value to the displayed text
String viewText = "Items from " + atts.getValue("name") + ":";
brandView.setText(viewText);
//add the new view to the list
theViews.add(brandView);
}
//the element is a product
else if(qName.equals("product"))
isProduct = true;
}
//closing element tag
public void endElement (String uri, String name, String qName)
{
//handle the end of an element
if(qName.equals("brand"))
{
//create a View item for the products
TextView productView = new TextView(theContext);
productView.setTextColor(Color.rgb(192, 199, 95));
//display the compiled items
productView.setText(currBrand);
//add to the list
theViews.add(productView);
//reset the variable for future items
currBrand = "";
}
}
//element content
public void characters (char ch[], int start, int length)
{
//process the element content
//string to store the character content
String currText = "";
//loop through the character array
for (int i=start; i<start+length; i++)
{
switch (ch[i]) {
case '\\':
break;
case '"':
break;
case '\n':
break;
case '\r':
break;
case '\t':
break;
default:
currText += ch[i];
break;
}
}
//prepare for the next item
if(isProduct && currText.length()>0)
currBrand += currText+"\n";
}
public ArrayList<TextView> getData()
{
//take care of SAX, input and parsing errors
try
{
//set the parsing driver
System.setProperty("org.xml.sax.driver","org.xmlpull.v1.sax2.Driver");
//create a parser
SAXParserFactory parseFactory = SAXParserFactory.newInstance();
SAXParser xmlParser = parseFactory.newSAXParser();
//get an XML reader
XMLReader xmlIn = xmlParser.getXMLReader();
//instruct the app to use this object as the handler
xmlIn.setContentHandler(this);
//provide the name and location of the XML file **ALTER THIS FOR YOUR FILE**
URL xmlURL = new URL("http://mydomain.com/umesh.xml");
//open the connection and get an input stream
URLConnection xmlConn = xmlURL.openConnection();
InputStreamReader xmlStream = new InputStreamReader(xmlConn.getInputStream());
//build a buffered reader
BufferedReader xmlBuff = new BufferedReader(xmlStream);
// uuu XmlResourceParser todolistXml = getResources().getXml(R.raw.c4mh_clinics);
//parse the data
xmlIn.parse(new InputSource(xmlBuff));
}
catch(SAXException se) { Log.e("AndroidTestsActivity",
"SAX Error " + se.getMessage()); }
catch(IOException ie) { Log.e("AndroidTestsActivity",
"Input Error " + ie.getMessage()); }
catch(Exception oe) { Log.e("AndroidTestsActivity",
"Unspecified Error " + oe.getMessage()); }
//return the parsed product list
return theViews;
}
}
XMLParsing.java
package com.umesh.xmlparsing;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.TextView;
public class XMLParsing extends Activity {
TextView tv;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//get a reference to the layout
LayoutInflater inflater = getLayoutInflater();
LinearLayout mainLayout = (LinearLayout) inflater.inflate(R.layout.main,null);
try
{
//create an instance of the DefaultHandler class
//**ALTER THIS FOR YOUR CLASS NAME**
DataHandler handler = new DataHandler(getApplicationContext());
//get the string list by calling the public method
ArrayList<TextView> newViews = handler.getData();
//convert to an array
Object[] products = newViews.toArray();
//loop through the items, creating a View item for each
for(int i=0; i<products.length; i++)
{
//add the next View in the list
mainLayout.addView((TextView)products[i]);
}
}
catch(Exception pce) { Log.e("AndroidTestsActivity", "PCE "+pce.getMessage()); }
setContentView(mainLayout);
}
}
Please See below link of my answer, it will solve your problem.
Local XML Parsing
I am developing an application in which i need to read a resource file. I am saving my file (named "sample")in raw directory of res folder. When i tried to access it in code, by writing its resource id as R.raw.sample , it gives the following error.
Error(30,60)Cannot find symbol variable raw.
I am using intellij idea 11.0.3 and platform for android is 2.3.3.
The code is as follows...
package com.example;
import android.content.Context;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class SampleLoader {
public SampleLoader(){
}
public static int[] readFromFile(Context ctx, int resId){
String sample = readRawTextFile(ctx,resId);
int [] arr = stringToIntArray(sample);
return arr;
}
public static String readRawTextFile(Context ctx, int resId)
{
InputStream inputStream = ctx.getResources().openRawResource(resId);
InputStreamReader inputReader = new InputStreamReader(inputStream);
BufferedReader buffReader = new BufferedReader(inputReader);
String line;
StringBuilder text = new StringBuilder();
try {
//while (( line = buffReader.readLine()) != null) {
if (( line = buffReader.readLine()) != null) {
text.append(line);
//text.append('\n');
}
} catch (IOException e) {
return null;
}
return text.toString();
}
public static int[] stringToIntArray(String line){
int[] sample = new int[line.length()-2];
String s ;
for (int i=0; i<line.length(); i++)
{
if(i>1)
{ sample[i] = Character.getNumericValue(line.charAt(i));
}
}
return sample;
}
public void populateListOfSamples(){
}
}
package com.example;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MyActivity extends Activity {
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(createContent());
}
LinearLayout createContent(){
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
ViewGroup.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.FILL_PARENT);
linearLayout.setLayoutParams(params);
final int[] arr6 = SampleLoader.readFromFile(this,R.raw.sample) ;
final Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.no3);
final ImageView imageView1 = new ImageView(this);
imageView1.setVisibility(View.INVISIBLE);
final TextView textView = new TextView(this);
String str2 = "Byte Array will appear here!";
textView.setText(str2);
final Button btn2 = new Button(this);
final Button btn = new Button(this);
btn.setText("Convert Pic to Byte Array");
btn.setOnClickListener(new View.OnClickListener() { //Event handler for click event.
public void onClick(View v) {
textView.setText(str3);
btn2.setVisibility(View.VISIBLE);
}
});
btn2.setText("Convert Byte Array to Pic");
btn2.setVisibility(View.INVISIBLE);
btn2.setOnClickListener(new View.OnClickListener() { //Event handler for click event.
public void onClick(View v) {
btn.setVisibility(View.INVISIBLE);
final Bitmap imag = filing.arrtoimg(arr6);
textView.setVisibility(View.INVISIBLE);
imageView1.setVisibility(View.VISIBLE);
imageView1.setImageBitmap(imag);
}
});
linearLayout.addView(imageView1);
linearLayout.addView(btn);
linearLayout.addView(btn2);
linearLayout.addView(textView);
return linearLayout;
}
}
I need to show toast message when the server is not responding
when I press the login button, some parameters are passed to AgAppMenu screen which use url connection to server and get xml response in AgAppHelperMethods screen. The
probelm is when the server is busy or the network is not avaibale, I can't show toast message on catch block although it shows the log message.
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent ;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class LoginScreen extends Activity implements OnClickListener {
EditText mobile;
EditText pin;
Button btnLogin;
Button btnClear;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.agapplogin);
TextView lblMobileNo = (TextView) findViewById(R.id.lblMobileNo);
lblMobileNo.setTextColor(getResources()
.getColor(R.color.text_color_red));
mobile = (EditText) findViewById(R.id.txtMobileNo);
TextView lblPinNo = (TextView) findViewById(R.id.lblPinNo);
lblPinNo.setTextColor(getResources().getColor(R.color.text_color_red));
pin = (EditText) findViewById(R.id.txtPinNo);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnClear = (Button) findViewById(R.id.btnClear);
btnLogin.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
postLoginData();
}
});
btnClear.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
cleartext();
}
});
/*
*
* btnClear.setOnClickListener(new OnClickListener() { public void
* onClick(View arg0) {
*
* } });
*/
}
public void postLoginData()
{
if (pin.getTextSize() == 0 || mobile.getTextSize() == 0) {
AlertDialog.Builder altDialog = new AlertDialog.Builder(this);
altDialog.setMessage("Please Enter Complete Information!");
} else {
Intent i = new Intent(this.getApplicationContext(), AgAppMenu.class);
Bundle bundle = new Bundle();
bundle.putString("mno", mobile.getText().toString());
bundle.putString("pinno", pin.getText().toString());
i.putExtras(bundle);
startActivity(i);
}
}
#Override
public void onClick(View v) {
}
public void cleartext() {
{
pin.setText("");
mobile.setText("");
}
}
}
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class AgAppMenu extends Activity {
String mno, pinno;
private String[][] xmlRespone;
Button btnMiniStatement;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.agappmenu);
mno = getIntent().getExtras().getString("mno");
pinno = getIntent().getExtras().getString("pinno");
setTitle("Welcome to the Ag App Menu");
AgAppHelperMethods agapp =new AgAppHelperMethods();
// xmlRespone = AgAppHelperMethods.AgAppXMLParser("AG_IT_App/AgMainServlet?messageType=LOG&pin=" + pinno + "&mobile=" + mno + "&source=" + mno + "&channel=INTERNET");
xmlRespone = agapp.AgAppXMLParser("AG_IT_App/AgMainServlet?messageType=LOG&pin=" + pinno + "&mobile=" + mno + "&source=" + mno + "&channel=INTERNET");
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import android.view.View;
import android.view.View.OnKeyListener;
public class AgAppHelperMethods extends Activity {
private static final String LOG_TAG = null;
private static AgAppHelperMethods instance = null;
public static String varMobileNo;
public static String varPinNo;
String[][] xmlRespone = null;
boolean flag = true;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.agapphelpermethods);
}
protected AgAppHelperMethods() {
}
public static AgAppHelperMethods getInstance() {
if (instance == null) {
instance = new AgAppHelperMethods();
}
return instance;
}
public static String getUrl() {
String url = "https://demo.accessgroup.mobi/";
return url;
}
public String[][] AgAppXMLParser(String parUrl) {
String _node, _element;
String[][] xmlRespone = null;
try {
String url = AgAppHelperMethods.getUrl() + parUrl;
URL finalUrl = new URL(url);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(finalUrl.openStream()));
doc.getDocumentElement().normalize();
NodeList list = doc.getElementsByTagName("*");
_node = new String();
_element = new String();
xmlRespone = new String[list.getLength()][2];
// this "for" loop is used to parse through the
// XML document and extract all elements and their
// value, so they can be displayed on the device
for (int i = 0; i < list.getLength(); i++) {
Node value = list.item(i).getChildNodes().item(0);
_node = list.item(i).getNodeName();
_element = value.getNodeValue();
xmlRespone[i][0] = _node;
xmlRespone[i][1] = _element;
}// end for
throw new ArrayIndexOutOfBoundsException();
}// end try
// will catch any exception thrown by the XML parser
catch (Exception e) {
Toast.makeText(AgAppHelperMethods.this,
"error server not responding " + e.getMessage(),
Toast.LENGTH_SHORT).show();
Log.e(LOG_TAG, "CONNECTION ERROR FUNDAMO SERVER NOT RESPONDING", e);
}
// Log.e(LOG_TAG, "CONNECTION ERROR FUNDAMO SERVER NOT RESPONDING", e);
return xmlRespone;
}
`
AgAppHelperMethods isn't really an Activity. You've derived this class from Activity, but then you've created Singleton management methods (getInstance()) and you are instantiating it yourself. This is bad. Don't do this.
Normally Android controls the instantiation of activities. You don't ever create one yourself (with new).
It looks to me like AgAppHelperMethods just needs to be a regular Java class. It doesn't need to inherit from anything. Remove also the lifecycle methods like onCreate().
Now you will have a problem with the toast, because you need a context for that and AgAppHelperMethods isn't a Context. To solve that you can add Context as a parameter to AgAppXMLParser() like this:
public String[][] AgAppXMLParser(Context context, String parUrl) {
...
// Now you can use "context" to create your toast.
}
When you call AgAppXMLParser() from AgAppMenu just pass "this" as the context parameter.