Tuesday, 28 February 2012

Write into or create Text File on android internal or External Storage


try {
if (writeFile("sdcard/strs.txt", "My string runs here"))
Log.i("WriteFil", "Success");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


Here the method:



/**
* This method to create text file or append to a text file
*
* @param fullFileLocationBathWithNameAndExten
* like "sdcard/strs.txt"
* @param text
* : the text which will be written in the file
* @return: sucess if the process finished successfully
* @throws IOException
* : error in creating the file
*/
public boolean writeFile(String fullFileLocationBathWithNameAndExten,
String text) throws IOException {
File file = new File(fullFileLocationBathWithNameAndExten);
if (!file.exists()) {

file.createNewFile();

}

// BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(file, true));
buf.append(text);
buf.newLine();
buf.close();

return true;

}

Sunday, 26 February 2012

Catch Mutliple ListViews events in the same activity

Dears,

Maybe you want to create many ListViews Dynamically, and you want to catch their events in single listener, you can do that in both ways: if you know the list adapter object name or list object name in
let us assume we have 3 listViews
lv1,lv2,lv3 and 3 lists adapters
la1, la2, la3

we want to set the list item adpaterslike this
lv1.setAdapter(la1);
lv2.setAdapter(la2);
lv3.setAdapter(la3);

and listeners
lv1.setOnItemClickListener(this);
lv2.setOnItemClickListener(this);
lv3.setOnItemClickListener(this);

public void onItemClick(AdapterView parent, View selectedView,
int selectedViewPos, long rowId) {
MyListAdapter myListAdapter = (MyListAdapter) ((ListView) selectedView
.getParent()).getAdapter();
if(myListAdapter==la1){
//write each list item event here or write your code for list1
}else if(myListAdapter==la2){
//write each list item event here or write your code for list2
}else if(myListAdapter==la3){
//write each list item event here or write your code for list3
}

//or

public void onItemClick(AdapterView parent, View selectedView,
int selectedViewPos, long rowId) {
ListView myListView =((ListView) selectedView.getParent());
if(myListView ==lv1){
//write each list item here event or write your code for list1
}else if(myListView ==lv2){
//write each list item here event or write your code for list2
}else if(myListView ==lv3){
//write each list item here event or write your code for list3
}




Mohammad Abu Hmead

Wednesday, 22 February 2012

Android add Tabs from other xml Layouts

The big question which made fire my crazy is: how to add tabs to the TabHost from other xml layouts?

I searched and searched much times and finally I tried something and I had succeed.

The Step to have tabs from other xml layouts:
1- Add tab host to your layout -main_window-
2- Create your separate XML layout file
3- Inflate it to view in java code.
4- Override createTabContent and return the inflated view.
5- Add the view to the TabSpec.
Look @ the code bellow

setContentView(R.layout.main_window);
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View row = layoutInflater.inflate(R.layout.mySeperatedXMLLayout,null);
ListView leftList = (ListView) row.findViewById(R.id.leftList);
leftList .setAdapter(new IconAndTextListAdapter(getBaseContext(),
R.layout.icon_and_text, new Contents()
.getCountriesFlagsLinks("en"), new Contents()
.getCountriesNames("en"), R.id.icon_view,
R.id.text_view));

ListView categoriesList = (ListView) row.findViewById(R.id.rightList);
categoriesList.setAdapter(new IconAndTextListAdapter(getBaseContext(),
R.layout.icon_and_text, new Contents()
.getCountriesFlagsLinks("en"), new Contents()
.getCountriesNames("en"), R.id.icon_view,
R.id.text_view));

TabHost tabHost = (TabHost) findViewById(android.R.id.tabhost);
tabHost.setup();
TabSpec setContent = tabHost.newTabSpec("Tab1")
.setIndicator("Countries").setContent(new TabHost.TabContentFactory() {
public View createTabContent(String tag) {
return row;
}});
tabHost.addTab(setContent);


double_lists_holder.xml
// Comment

android:id="@+id/doubList_tbL"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/rock_bg"
android:stretchColumns="0" >



android:id="@+id/leftList"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_marginLeft="10dp"
android:layout_marginRight="5dp"
android:layout_weight=".50"
android:cacheColorHint="#00000000"
android:divider="@drawable/list_divider"
android:dividerHeight="10dp"
android:drawSelectorOnTop="false"
android:listSelector="@drawable/free_ico_color5"
android:scrollbars="vertical"
android:soundEffectsEnabled="true" />

android:id="@+id/rightList"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_marginLeft="5dp"
android:layout_marginRight="10dp"
android:layout_weight=".50"
android:cacheColorHint="#00000000"
android:drawSelectorOnTop="false"
android:listSelector="@drawable/paid_ico_color3"
android:scrollbars="vertical"
android:soundEffectsEnabled="true" />





main_window.xml
// Comment

android:layout_width="fill_parent"
android:layout_height="fill_parent" >

android:id="@android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@+id/googlAd_view"
android:layout_alignParentTop="true" >

android:id="@+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

android:id="@android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" >


android:id="@android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent" >






Mohammad Abu Hmead

IconAndTextListAdapter

// Comment
public class IconAndTextListAdapter extends ArrayAdapter {

private final Context context;
private final String[] strings;
private final int[] iconsIDs;
private final int rowLayoutID, iconViewID, textViewID;
private View rowView ;


/**
* @param context
* @param rowLayoutID
* @param iconsIDs
* @param strings
* @param iconViewID
* @param textViewID
*/
public IconAndTextListAdapter(Context context, int rowLayoutID,
int[] iconsIDs, String[] strings, int iconViewID, int textViewID) {
super(context, rowLayoutID, strings);
this.context = context;
this.strings = strings;
this.iconsIDs = iconsIDs;
this.rowLayoutID = rowLayoutID;
this.iconViewID = iconViewID;
this.textViewID = textViewID;
// TODO Auto-generated constructor stub
}
static class ViewHolder {
public TextView text;
public ImageView image;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(rowLayoutID, null);
ViewHolder viewHolder = new ViewHolder();
viewHolder.text = (TextView) rowView.findViewById(textViewID);
viewHolder.image = (ImageView) rowView.findViewById(iconViewID);
rowView.setTag(viewHolder);

}

ViewHolder holder = (ViewHolder) rowView.getTag();

holder.text.setText(strings[position]);

holder.image.setImageResource(iconsIDs[position]);

return rowView;
}

}



Mohammad Abu Hmead

Tuesday, 10 January 2012

Select random rows in SQL server


USE [DBName]

SELECT TOP 1 ID,targetLink,addPath,add_type

from dbo.advertisements

where targetDevices=@targetDevices

ORDER BY newid()


Mohammad Abu Hmead

Split method, for java and j2me and android

public Vector split(String stringToBeSplitted, String delimiter) {
Vector vector = new Vector();
StringBuffer sb = new StringBuffer();
int delimiterIndex = stringToBeSplitted.indexOf(delimiter), delemitterLength = delimiter
.length();
if (delimiterIndex != -1) {
while (delimiterIndex != -1) {
sb.append(stringToBeSplitted.substring(0, delimiterIndex));
stringToBeSplitted = stringToBeSplitted.substring(sb.length()
+ delemitterLength, stringToBeSplitted.length());
vector.addElement(sb.toString());
// System.out.println(sb.toString());
sb.delete(0, sb.length());
delimiterIndex = stringToBeSplitted.indexOf(delimiter);
}
vector.addElement(stringToBeSplitted);
// System.out.println((String)vector.elementAt((vector.size()-1)));
} else {
vector.addElement(stringToBeSplitted);
}
sb = null;
stringToBeSplitted = null;
delimiter = null;
delemitterLength = 0;
delimiterIndex = 0;
return vector;
}

Mohammad Abu Hmead

Send text to servlet and get response code from servlet

import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.io.*;
import java.io.*;
import java.util.Vector;

public class MidletServlet extends MIDlet implements CommandListener {
Display display = null;
Form form = null;
TextField tb = null;
String str = null;
String url = "http://localhost:8080/servlets-examples/servlet/getText";
Command backCommand = new Command("Back", Command.BACK, 0);
Command submitCommand = new Command("Submit", Command.OK, 2);
Command exitCommand = new Command("Exit", Command.STOP, 3);
private Test test;

public MidletServlet() {}

public void startApp() throws MIDletStateChangeException {
display = Display.getDisplay(this);
form = new Form("Request Servlet");
tb = new TextField("Please input text: ","",30,TextField.ANY );
form.append(tb);
form.addCommand(submitCommand);
form.addCommand(exitCommand);
form.setCommandListener(this);
display.setCurrent(form);
}

public void pauseApp() {}

public void destroyApp(boolean unconditional) {}

public void commandAction(Command c, Displayable d) {
if (c == exitCommand) {
destroyApp(true);
notifyDestroyed();
} else if (c == backCommand) {
display.setCurrent(form);
} else if (c == submitCommand) {
str = tb.getString();
test = new Test(this);
test.start();
test.getServlet(str);
}
}


class Test implements Runnable {
MidletServlet midlet;
private Display display;
String text;

public Test(MidletServlet midlet) {
this.midlet = midlet;
display = Display.getDisplay(midlet);
}

public void start() {
Thread t = new Thread(this);
t.start();
}

public void run() {
StringBuffer sb = new StringBuffer();
try {
HttpConnection c = (HttpConnection) Connector.open(url);
c.setRequestProperty(
"User-Agent","Profile/MIDP-1.0, Configuration/CLDC-1.0");

c.setRequestProperty("Content-Language","en-US");
c.setRequestMethod(HttpConnection.POST);

DataOutputStream os =
(DataOutputStream)c.openDataOutputStream();

os.writeUTF(text.trim());
os.flush();
os.close();

// Get the response from the servlet page.
DataInputStream is =(DataInputStream)c.openDataInputStream();
//is = c.openInputStream();
int ch;
sb = new StringBuffer();
while ((ch = is.read()) != -1) {
sb.append((char)ch);
}
showAlert(sb.toString());
is.close();
c.close();
} catch (Exception e) {
showAlert(e.getMessage());
}
}
/* This method takes input from user like text and pass
to servlet */
public void getServlet(String text) {
this.text = text;
}

/* Display Error On screen*/
private void showAlert(String err) {
Alert a = new Alert("");
a.setString(err);
a.setTimeout(Alert.FOREVER);
display.setCurrent(a);
}
};
}
import java.io.*;
import java.text.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class getText extends HttpServlet {

public void init() {
}

public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {

DataInputStream in =
new DataInputStream((InputStream)request.getInputStream());

String text = in.readUTF();
String message;
try {
message = "100 ok";
} catch (Throwable t) {
message = "200 " + t.toString();
}
response.setContentType("text/plain");
response.setContentLength(message.length());
PrintWriter out = response.getWriter();
out.println(message);
in.close();
out.close();
out.flush();
}

public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {

doPost(request,response);
}
}


Mohammad Abu Hmead
10.01.2012 11:08 AM