.DS_Store application/cache/* !application/cache/index.html !application/cache/.htaccess application/logs/* !application/logs/index.html !application/logs/.htaccess
Saturday, November 29, 2014
.gitignore file examples
Tuesday, November 25, 2014
how to build and deploy apk file into android emulator in netbeans
android project install.bat file
@echo off
echo.
echo Current android project folder Build and Install...
echo by %0
echo.
echo -------------------------------------------------------------------Building
echo.
call "C:\Program Files\NetBeans 8.0.2\extide\ant\bin\ant" -f "%cd%" clean debug
echo.
echo -----------------------------------------------------------------Installing
echo.
adb -s emulator-5554 install -r bin\%~n0.apk
echo.
@echo off
echo.
echo Current android project folder Build and Install...
echo by %0
echo.
echo -------------------------------------------------------------------Building
echo.
call "C:\Program Files\NetBeans 8.0.2\extide\ant\bin\ant" -f "%cd%" clean debug
echo.
echo -----------------------------------------------------------------Installing
echo.
adb -s emulator-5554 install -r bin\%~n0.apk
echo.
how to center relative layout in linearlayout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/BaseLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/mainmenu_background" >
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="fitXY"
android:src="@drawable/main_menu_background" />
<LinearLayout
android:id="@+id/l1"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:orientation="vertical" >
<!-- Top menu -->
<LinearLayout
android:id="@+id/l2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<RelativeLayout
android:id="@+id/TopMenuHolder"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/main_menu_background_header"
android:gravity="left"
android:orientation="horizontal"
android:visibility="visible" >
<ImageView
android:id="@+id/logo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:src="@drawable/logo" />
<LinearLayout
android:id="@+id/TopRightButtonsHolder"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:orientation="horizontal"
android:visibility="visible" >
<RelativeLayout
android:id="@+id/sinscrire"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageButton
android:id="@+id/login_registerbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:background="@color/transparent"
android:scaleType="fitXY"
android:src="@drawable/main_menu_sinscrire_button" />
<TextView
android:id="@+id/sinscrire_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/cpr_sinscrite_title_text"
android:textColor="@color/cpr_menubutton_black"
android:textSize="@dimen/cpr_small_menubutton_title_text_size"
android:textStyle="bold|italic" />
</RelativeLayout>
<RelativeLayout
android:id="@+id/connexion"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageButton
android:id="@+id/login_loginbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:background="@color/transparent"
android:scaleType="fitXY"
android:src="@drawable/main_menu_logout_button" />
<TextView
android:id="@+id/connexion_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/cpr_connexion_title_text"
android:textColor="@color/cpr_menubutton_white"
android:textSize="@dimen/cpr_small_menubutton_title_text_size"
android:textStyle="bold|italic" />
</RelativeLayout>
</LinearLayout>
</RelativeLayout>
</LinearLayout>
<!-- End of Top menu -->
<!-- Middle menu -->
<LinearLayout
android:id="@+id/l3"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_gravity="center_vertical|center_horizontal"
android:orientation="vertical" >
<RelativeLayout
android:id="@+id/MiddleMenu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal" >
<LinearLayout
android:id="@+id/MiddleLeftButtonsHolder"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:orientation="horizontal"
android:visibility="visible" >
<RelativeLayout
android:id="@+id/Parametres"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageButton
android:id="@+id/optionsmenu_settings"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:background="@color/transparent"
android:scaleType="fitXY"
android:src="@drawable/main_menu_options_button" />
<LinearLayout
android:id="@+id/options_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_gravity="left"
android:orientation="horizontal" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/options_icon" />
<TextView
android:id="@+id/parametres_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/cpr_parametres_title_text"
android:textColor="@color/cpr_menubutton_black"
android:textSize="@dimen/cpr_small_menubutton_title_text_size"
android:textStyle="bold|italic" />
</LinearLayout>
</RelativeLayout>
<RelativeLayout
android:id="@+id/Aide"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageButton
android:id="@+id/optionsmenu_info"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:background="@color/transparent"
android:scaleType="fitXY"
android:src="@drawable/main_menu_help_button" />
<LinearLayout
android:id="@+id/help_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_gravity="left"
android:orientation="horizontal" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/help_icon" />
<TextView
android:id="@+id/aide_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/cpr_aide_title_text"
android:textColor="@color/cpr_menubutton_black"
android:textSize="@dimen/cpr_small_menubutton_title_text_size"
android:textStyle="bold|italic" />
</LinearLayout>
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:id="@+id/MiddleRightButtonsHolder"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="@id/MiddleLeftButtonsHolder"
android:orientation="horizontal"
android:visibility="visible" >
<RelativeLayout
android:id="@+id/Caisse"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageButton
android:id="@+id/cashiericon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:background="@color/transparent"
android:scaleType="fitXY"
android:src="@drawable/main_menu_cashier_button" />
<LinearLayout
android:id="@+id/caisse_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_gravity="left"
android:orientation="horizontal" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/cashier_icon" />
<TextView
android:id="@+id/caisse_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/cpr_caisse_title_text"
android:textColor="@color/cpr_menubutton_white"
android:textSize="@dimen/cpr_small_menubutton_title_text_size"
android:textStyle="bold|italic" />
</LinearLayout>
</RelativeLayout>
</LinearLayout>
</RelativeLayout>
<!-- End of Middle menu -->
<!-- Main menu -->
<RelativeLayout
android:id="@+id/MainMenu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/MiddleMenu"
android:layout_marginBottom="5dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp" >
<ImageView
android:id="@+id/main_menu_black_rect"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:scaleType="fitXY"
android:src="@drawable/main_menu_black_rect" />
<RelativeLayout
android:id="@+id/play_for_real"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginTop="20dp" >
<ImageButton
android:id="@+id/realmoneybutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:background="@color/transparent"
android:scaleType="fitStart"
android:src="@drawable/main_menu_play_for_real_button" />
<ImageView
android:id="@+id/play_for_real_img_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@id/realmoneybutton"
android:layout_alignRight="@id/realmoneybutton"
android:background="@color/transparent"
android:src="@drawable/main_menu_play_for_real_button_icon" />
<LinearLayout
android:id="@+id/play_for_money_text_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:orientation="vertical" >
<TextView
android:id="@+id/play_for_real_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/cpr_play_for_real_title_text"
android:textColor="@color/cpr_menubutton_white"
android:textSize="@dimen/cpr_menubutton_title_text_size"
android:textStyle="bold" />
<TextView
android:id="@+id/play_for_real_desc"
android:layout_width="221dp"
android:layout_height="wrap_content"
android:text="@string/cpr_play_for_real_title_desc"
android:textColor="@color/cpr_menubutton_white"
android:textSize="@dimen/cpr_menubutton_desc_text_size" />
</LinearLayout>
</RelativeLayout>
<RelativeLayout
android:id="@+id/play_for_fun"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/play_for_real"
android:layout_marginLeft="15dp"
android:layout_marginTop="5dp" >
<ImageButton
android:id="@+id/playmoneybutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:background="@color/transparent"
android:scaleType="fitXY"
android:src="@drawable/main_menu_play_for_fun_button" />
<ImageView
android:id="@+id/play_for_fun_img_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@id/playmoneybutton"
android:layout_alignRight="@id/playmoneybutton"
android:background="@color/transparent"
android:src="@drawable/main_menu_play_for_fun_button_icon" />
<LinearLayout
android:id="@+id/play_for_fun_text_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:orientation="vertical" >
<TextView
android:id="@+id/play_for_fun_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/cpr_play_for_fun_title_text"
android:textColor="@color/cpr_menubutton_white"
android:textSize="@dimen/cpr_menubutton_title_text_size"
android:textStyle="bold" />
<TextView
android:id="@+id/play_for_fun_desc"
android:layout_width="221dp"
android:layout_height="wrap_content"
android:text="@string/cpr_play_for_fun_title_desc"
android:textColor="@color/cpr_menubutton_white"
android:textSize="@dimen/cpr_menubutton_desc_text_size" />
</LinearLayout>
</RelativeLayout>
<RelativeLayout
android:id="@+id/tutoriel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/play_for_fun"
android:layout_marginLeft="15dp"
android:layout_marginTop="5dp" >
<ImageButton
android:id="@id/previewbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:background="@color/transparent"
android:scaleType="fitXY"
android:src="@drawable/main_menu_tutorial_button" />
<TextView
android:id="@+id/tutoriel_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:text="@string/cpr_tutoriel_title_text"
android:textColor="@color/cpr_menubutton_white"
android:textSize="@dimen/cpr_menubutton_title_text_size"
android:textStyle="bold" />
</RelativeLayout>
</RelativeLayout>
</LinearLayout>
<!-- End of Main menu -->
</LinearLayout>
<!-- End of Main Container -->
</RelativeLayout>
Difference between px, dp, dip and sp in Android?
px
Pixels - corresponds to actual pixels on the screen.
in
Inches - based on the physical size of the screen.
1 Inch = 2.54 centimeters
mm
Millimeters - based on the physical size of the screen.
pt
Points - 1/72 of an inch based on the physical size of the screen.
dp
Density-independent Pixels - an abstract unit that is based on the physical density of the screen. These units are relative to a 160 dpi screen, so one dp is one pixel on a 160 dpi screen. The ratio of dp-to-pixel will change with the screen density, but not necessarily in direct proportion. Note: The compiler accepts both "dip" and "dp", though "dp" is more consistent with "sp".
sp
Scale-independent Pixels - this is like the dp unit, but it is also scaled by the user's font size preference. It is recommend you use this unit when specifying font sizes, so they will be adjusted for both the screen density and user's preference.
Monday, November 24, 2014
python file input output example
def print_numbers(numbers): print("Telephone Numbers:") for k, v in numbers.items(): print("Name:", k, "\tNumber:", v) print() def add_number(numbers, name, number): numbers[name] = number def lookup_number(numbers, name): if name in numbers: return "The number is " + numbers[name] else: return name + " was not found" def remove_number(numbers, name): if name in numbers: del numbers[name] else: print(name," was not found") def load_numbers(numbers, filename): in_file = open(filename, "rt") while True: in_line = in_file.readline() if not in_line: break in_line = in_line[:-1] name, number = in_line.split(",") numbers[name] = number in_file.close() def save_numbers(numbers, filename): out_file = open(filename, "wt") for k, v in numbers.items(): out_file.write(k + "," + v + "\n") out_file.close() def print_menu(): print('1. Print Phone Numbers') print('2. Add a Phone Number') print('3. Remove a Phone Number') print('4. Lookup a Phone Number') print('5. Load numbers') print('6. Save numbers') print('7. Quit') print() phone_list = {} menu_choice = 0 print_menu() while True: menu_choice = int(input("Type in a number (1-7): ")) if menu_choice == 1: print_numbers(phone_list) elif menu_choice == 2: print("Add Name and Number") name = input("Name: ") phone = input("Number: ") add_number(phone_list, name, phone) elif menu_choice == 3: print("Remove Name and Number") name = input("Name: ") remove_number(phone_list, name) elif menu_choice == 4: print("Lookup Number") name = input("Name: ") print(lookup_number(phone_list, name)) elif menu_choice == 5: filename = input("Filename to load: ") load_numbers(phone_list, filename) elif menu_choice == 6: filename = input("Filename to save: ") save_numbers(phone_list, filename) elif menu_choice == 7: break else: print_menu() print("Goodbye")
Sunday, November 23, 2014
How to use JSON to parse data into android application using Http Client Get
MainActivity.java
package com.test.jsonparser;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.jitesh.androidjsonparser.R;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class MainActivity extends ListActivity {
private Context context;
private static String url = "http://docs.blackberry.com/sampledata.json";
private static final String VTYPE = "Type";
private static final String VCOLOR = "Color";
private static final String FUEL = "Fuel";
private static final String TREAD = "Tread";
ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
ListView lv ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new ProgressTask(MainActivity.this).execute();
}
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
private ListActivity activity;
// private List<Message> messages;
public ProgressTask(ListActivity activity) {
this.activity = activity;
context = activity;
dialog = new ProgressDialog(context);
}
private Context context;
protected void onPreExecute() {
this.dialog.setMessage("Progress start");
this.dialog.show();
}
@Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
ListAdapter adapter = new SimpleAdapter(context, jsonlist,
R.layout.list_item, new String[] { VTYPE, VCOLOR,
FUEL, TREAD }, new int[] {
R.id.vehicleType, R.id.vehicleColor, R.id.fuel,
R.id.treadType });
setListAdapter(adapter);
// select single ListView item
lv = getListView();
}
protected Boolean doInBackground(final String... args) {
JSONParser jParser = new JSONParser();
// get JSON data from URL
JSONArray json = jParser.getJSONFromUrl(url);
for (int i = 0; i < json.length(); i++) {
try {
JSONObject c = json.getJSONObject(i);
String vtype = c.getString(VTYPE);
String vcolor = c.getString(VCOLOR);
String vfuel = c.getString(FUEL);
String vtread = c.getString(TREAD);
HashMap<String, String> map = new HashMap<String, String>();
// Add child node to HashMap key & value
map.put(VTYPE, vtype);
map.put(VCOLOR, vcolor);
map.put(FUEL, vfuel);
map.put(TREAD, vtread);
jsonlist.add(map);
}
catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
}
}
JSONParser.java
package com.test.jsonparser;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import android.util.Log;
public class JSONParser {
static InputStream iStream = null;
static JSONArray jarray = null;
static String json = "";
public JSONParser() {
}
public JSONArray getJSONFromUrl(String url) {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
Log.e("==>", "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Parse String to JSON object
try {
jarray = new JSONArray( builder.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jarray;
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jitesh.androidjsonparser"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.test.jsonparser.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
string.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Vehicle Information</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
</resources>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<!-- Main ListView
Always give id value as list(@android:id/list)
-->
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
Android - Read an XML file with HTTP GET
MainActivity.java package com.hmkcode.android;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import org.apache.http.HttpResponse;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.DefaultHttpClient;import android.net.ConnectivityManager;import android.net.NetworkInfo;import android.os.AsyncTask;import android.os.Bundle;import android.util.Log;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast;import android.app.Activity;public class MainActivity extends Activity { EditText etResponse; TextView tvIsConnected; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // get reference to the views etResponse = (EditText) findViewById(R.id.etResponse); tvIsConnected = (TextView) findViewById(R.id.tvIsConnected); // check if you are connected or not if(isConnected()){ tvIsConnected.setBackgroundColor(0xFF00CC00); tvIsConnected.setText("You are conncted"); } else{ tvIsConnected.setText("You are NOT conncted"); } // show response on the EditText etResponse //etResponse.setText(GET("http://hmkcode.com/examples/index.php")); // call AsynTask to perform network operation on separate thread } public static String GET(String url){ InputStream inputStream = null; String result = ""; try { // create HttpClient HttpClient httpclient = new DefaultHttpClient(); // make GET request to the given URL HttpResponse httpResponse = httpclient.execute(new HttpGet(url)); // receive response as inputStream inputStream = httpResponse.getEntity().getContent(); // convert inputstream to string if(inputStream != null) result = convertInputStreamToString(inputStream); else result = "Did not work!"; } catch (Exception e) { Log.d("InputStream", e.getLocalizedMessage()); } return result; } private static String convertInputStreamToString(InputStream inputStream) throws IOException{ BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream)); String line = ""; String result = ""; while((line = bufferedReader.readLine()) != null) result += line; inputStream.close(); return result; } public boolean isConnected(){ ConnectivityManager connMgr = (ConnectivityManager) getSystemService(this.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) return true; else return false; } private class HttpAsyncTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... urls) { return GET(urls[0]); } // onPostExecute displays the results of the AsyncTask. @Override protected void onPostExecute(String result) { Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show(); etResponse.setText(result); } }} AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> package="com.hmkcode.android" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.hmkcode.android.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application></manifest> XML parsing HttpGet uri = new HttpGet("http://example.com");
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse resp = client.execute(uri);
StatusLine status = resp.getStatusLine();
if (status.getStatusCode() != 200) {
Log.d(tag, "HTTP error, invalid server status code: " + resp.getStatusLine());
}
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(resp.getEntity().getContent());
Basic AUTH String auth = Base64Converter.encode(String.format("%s:%s", user, pass));
URL u = new URL(url);
conn = (HttpsURLConnection) u.openConnection();
conn.addRequestProperty("Authorization", "Basic " + auth);
Subscribe to:
Comments (Atom)
