Xml Parsing in android - android

guys I have a problem in my program that it returns an Exception as Unable to start activity and gives Force Close to my applicatio of Xml Parsing. Please review my code and help me.
code: package com.ex.createXml;
import java.net.URL;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;
public class XmlParsingExample extends Activity{
/*Create Object SitesList Class*/
SitesList siteslist = null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(1);
TextView name[];
TextView websites[];
TextView category[];
try{
/*Handling Xml*/
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
URL sourceurl = new URL("http://www.androidpeople.com/wp-content/uploads/2010/06/example.xml");
MyXmlHandler mxh = new MyXmlHandler();
xr.setContentHandler(mxh);
xr.parse(new InputSource(sourceurl.openStream()));
}catch(Exception e)
{
System.out.println("Xml Parsing Exception="+e);
}
siteslist = MyXmlHandler.siteslist;
name = new TextView[siteslist.getName().size()];
websites = new TextView[siteslist.getWebsite().size()];
category = new TextView[siteslist.getCategory().size()];
/** Set the result text in textview and add it to layout */
for (int i = 0; i < siteslist.getWebsite().size(); i++) {
name[i] = new TextView(this);
name[i].setText("Name = "+siteslist.getName().get(i));
websites[i] = new TextView(this);
websites[i].setText("Website = "+siteslist.getWebsite().get(i));
category[i] = new TextView(this);
category[i].setText("Website Category = "+siteslist.getCategory().get(i));
layout.addView(name[i]);
layout.addView(websites[i]);
layout.addView(category[i]);
}
setContentView(layout);
}
}

have u mentioned xmlParsingExample in manifeast file or not.as this is from android people & it will work fine so just check have u mentioned in manifeast or not.

Independently of your xml parsing, did you set internet permission for your activity (in the manifest)? See the android dev doc and set android.permission.INTERNET.
You try to get an xml file on http. As a consequence, if you don't allow the application to use internet…

Related

Insert image from mysql data base into ImageView android

I am trying to get an image from my data base and insert it using imageView in android
my php code:
<?php
if(isset($_POST["IdToSearch"]) && $_POST["IdToSearch"] != "") {
$firstid = $_POST["IdToSearch"];
$con = mysqli_connect("localhost","root","","bdUniv");
if(mysqli_connect_errno()) {
echo'Database connection error: '. mysqli_connect_error();
exit();
}
$firstid = mysqli_real_escape_string($con,$firstid);
$userdetails = mysqli_query($con,"SELECT * FROM Etudiant WHERE id = '$firstid'");
if(!$userdetails) {
echo'Couldnotrunquery: '. mysqli_error($con);
exit();
}
$row = mysqli_fetch_row($userdetails);
$result_data = array(
'id' => $row[0],
'nom' => $row[1],
'prenom' => $row[2],
'age' => $row[3],
'photo' => $row[4],
);
echo json_encode($result_data);
}else{
echo"Could not complete query. Missingparameter";
}
?>
My java code:
package com.example.getdatafrombdd;
import java.io.File;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity_GET extends Activity {
Button buttonGetData = null;
EditText editTextSearchString = null;
TextView textViewId = null;
TextView textViewNom = null;
TextView textViewPrenom = null;
TextView textViewAge = null;
ImageView imgViewPhoto = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity_get);
buttonGetData = (Button) findViewById(R.id.buttonGetData);
editTextSearchString = (EditText) findViewById(R.id.editTextSearchString);
textViewId = (TextView) findViewById(R.id.txtId);
textViewNom = (TextView) findViewById(R.id.txtNom);
textViewPrenom = (TextView) findViewById(R.id.txtPrenom);
textViewAge = (TextView) findViewById(R.id.txtAge);
imgViewPhoto = (ImageView) findViewById(R.id.imgPhoto);
//Setup the Button's OnClickListener
buttonGetData.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Get the data
DoPOST mDoPOST = new DoPOST(MainActivity_GET.this, editTextSearchString.getText().toString());
mDoPOST.execute("");
buttonGetData.setEnabled(false);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_activity__get, menu);
return true;
}
public class DoPOST extends AsyncTask<String, Void, Boolean> {
// String: le type des paramètres fournis à la tâche.
// Void: le type de données transmises durant la progression du traitement.
// Boolean: le type du résultat de la tâche.
Context mContext = null;
String IdToSearch = "";
//Result data
int intId;
String strNom;
String strPrenom;
int intAge;
String strPictPath;
Exception exception = null;
DoPOST(Context context, String nameToSearch) {
mContext = context;
IdToSearch = nameToSearch;
}
#Override
protected Boolean doInBackground(String... arg0) {
try{
//Setup the parameters
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
// key value
nameValuePairs.add(new BasicNameValuePair("IdToSearch", IdToSearch));
//Add more parameters as necessary
//Create the HTTP request
HttpParams httpParameters = new BasicHttpParams();
//Setup timeouts
HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
HttpConnectionParams.setSoTimeout(httpParameters, 15000);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
HttpPost httppost = new HttpPost("http://10.0.2.2/univ/getFromUniv.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
// Create a JSON object from the request response
JSONObject jsonObject = new JSONObject(result);
//Retrieve the data from the JSON object
intId = jsonObject.getInt("id");
strNom = jsonObject.getString("nom");
strPrenom = jsonObject.getString("prenom");
intAge = jsonObject.getInt("age");
strPictPath = jsonObject.getString("photo");
}catch (Exception e){
Log.e("ClientServerDemo", "Error:", e);
exception = e;
}
return true;
}
#Override
protected void onPostExecute(Boolean valid){
//Update the UI
textViewId.setText("Id: " + intId);
textViewNom.setText("Nom: " + strNom);
textViewPrenom.setText("Prenom: " + strPrenom);
textViewAge.setText("Age: " + intAge);
File imgFile = new File(strPictPath);
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
imgViewPhoto.setImageBitmap(myBitmap);
buttonGetData.setEnabled(true);
if(exception != null){
Toast.makeText(mContext, exception.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
}
When i compiled it i get the: id, name, 2nd name, age but no image found!
And the error is:
1-06 20:19:17.527: E/BitmapFactory(786): Unable to decode stream: java.io.FileNotFoundException: /home/user/images/myPict.jpg: open failed: ENOENT (No such file or directory)
Help please!
You are doing this very wrong. Your server is returning the path of the photo on the server, not in the app. When you go to open the file, your app gives you an error because the file is not found locally, which is where your app is looking. To fix this, you should either download the photo from the server in your AsyncTask or store the Internet path of your picture and use a library like Picasso to download the image at that path to the ImageView.
EDIT:
As #Zerkz noted in his comment, you could also pass the image contents itself in your JSON by encoding them in base64 and then decoding those contents to a Bitmap in your AsyncTask. This would be advantageous if you don't plan on publicly exposing the URL to any of your images or if they will eventually be stored in a database.

Android xml nullpointer exception xml parser

I'm using the sax xmlparser and I am unable to print results through toast. I get a null pointer exception. I found an example that uses textview array but I want to use toast. The original code from android people works fine, but if I apply the same code in my own project it fails everytime.
Main.java >
import java.net.URL;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.Toast;
public class Main extends Activity {
String strGK = null;
String strHWW = null;
String strHak5 = null;
CheckBox GK;
CheckBox HWW;
CheckBox Hak5;
SitesList sitesList = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void getUrl(View v) {
try {
/** Handling XML */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
/** Send URL to parse XML Tags */
URL sourceUrl = new URL("http://websitethatcontains/feed");
/** Create handler to handle XML Tags ( extends DefaultHandler ) */
MyXMLHandler myXMLHandler = new MyXMLHandler();
xr.setContentHandler(myXMLHandler);
xr.parse(new InputSource(sourceUrl.openStream()));
} catch (Exception e) {
System.out.println("XML Parsing Exception = " + e);
}
/** Get result from MyXMLHandler SitlesList Object */
sitesList = MyXMLHandler.sitesList;
/** Set the result text in textview and add it to layout */
for (int i = 0; i < sitesList.getName().size(); i++) { /** <- the prob. seems to be here */
Toast.makeText(getApplicationContext(), sitesList.getName().get(i), Toast.LENGTH_LONG).show();
}
}
}
try
public void getUrl(View v) {
MyXMLHandler myXMLHandler;
try {
/** Handling XML */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
/** Send URL to parse XML Tags */
URL sourceUrl = new URL("http://websitethatcontains/feed");
/** Create handler to handle XML Tags ( extends DefaultHandler ) */
myXMLHandler = new MyXMLHandler();
xr.setContentHandler(myXMLHandler);
xr.parse(new InputSource(sourceUrl.openStream()));
} catch (Exception e) {
System.out.println("XML Parsing Exception = " + e);
}
if (MyXMLHandler != null){
/** Get result from MyXMLHandler SitlesList Object */
sitesList = MyXMLHandler.sitesList;
/** Set the result text in textview and add it to layout */
for (int i = 0; i < sitesList.getName().size(); i++) { /** <- the prob. seems to be here */
Toast.makeText(getApplicationContext(), sitesList.getName().get(i), Toast.LENGTH_LONG).show();
}
}
}

Populating Spinner with JSON in Android 4.2 using AsyncTask

I am currently trying to translate the code for the MainActivity of an app that I created in API10 into API 16. From what I have read, I have to start using ASyncTask to access a URI and display the information on my app. I managed to do that in 2.3, but after translating it to JSON, I am now facing some roadblocks.
Essentially, what the app does is that, it takes a manifest code i.e. WAMF33000 and at the click of a button, the Spinner is populated with the jobs contained in that manifest. As I am fairly new to the concept of ASyncTask, I would like to understand how my code applies to the theory behind ASyncTask.
Based on my code, I have some questions:-
i) Which of my code in the ASyncTask is the parameter that is being passed?
ii) What is the progress value in my AsyncTask?
iii) Finally, is my return value the ArrayList of ManifestItems?
As of the 2.3 version, I invoke the JSON twice - once to load the consignments within the Manifest, and the second time to load details of a consignment selected in the spinner.
The following is my code:
package com.signonglass;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.*;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity
{
private final static String POD_URI = "http://192.168.0.105:8092/PodCore.svc";
private EditText evManifestCode;
private Spinner list_job;
private Button btnSubmit;
private String jobName;
private Button btnCons;
ArrayList<ManifestItemObj> jobList = new ArrayList<ManifestItemObj>();
ArrayList<ConsignmentItems> conItemList = new ArrayList<ConsignmentItems>();
Consignments retConsignment;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
evManifestCode = (EditText)findViewById(R.id.manifest);
btnSubmit = (Button)findViewById(R.id.btnSearchManifest);
list_job = (Spinner)findViewById(R.id.jobSpinner);
//tvView = (TextView)findViewById(R.id.deviceIdt);
//TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
//String IMEI_Number = telephonyManager.getDeviceId();
//tvView.setText("IMEI Number: " + IMEI_Number);
}
public class MyAsyncTask extends AsyncTask<String, Void, ArrayList<ManifestItemObj>>
{
protected void onPreExecute()
{
}
protected void onPostExecute(ArrayList<ManifestItemObj> jobList)
{
}
#Override
protected ArrayList<ManifestItemObj> doInBackground(String... params)
{
//http get request
HttpGet request = new HttpGet(POD_URI + "/getJobs/" + evManifestCode.getText().toString());
//set the hedear to get the data in JSON format
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
DefaultHttpClient client = new DefaultHttpClient();
String theString = new String("");
try
{
//get the response
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
is.close();
theString = builder.toString();
JSONObject jobsJSON = new JSONObject(theString);
JSONArray jobs = jobsJSON.getJSONArray("getJobsResult");
for(int i = 1; i < jobs.length(); i++)
{
JSONObject mit = jobs.getJSONObject(i);
ManifestItemObj mi = new ManifestItemObj();
mi.ManifestItemID = mit.getInt("ManifestItemID");
mi.JobType = mit.getString("JobType");
mi.FKID = mit.getInt("FKID");
jobList.add(mi);
}
}
catch (Exception e)
{
e.printStackTrace();
}
return jobList;
}
}
/*private void showToast(String msg)
{
// TODO Auto-generated method stub
Toast.makeText(this, "Toast: " + msg, Toast.LENGTH_LONG).show();
}*/
public void onViewConsignment(View view)
{
ShowItemsOfManifest(retConsignment);
}
public Consignments getConsignmentManifest(String consignment)
{
Consignments con = new Consignments();
try
{
DefaultHttpClient client = new DefaultHttpClient();
String theString = new String("");
//http get request
HttpGet request = new HttpGet(POD_URI + "/getJobDetails/" + consignment);
//set the hedear to get the data in JSON format
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
//get the response
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null)
{
builder.append(line);
}
is.close();
theString = builder.toString();
JSONObject conJSON = new JSONObject(theString);
JSONArray cons = conJSON.getJSONArray("getJobDetailsResult");
for(int i = 0; i < cons.length(); i++)
{
JSONObject cObj = cons.getJSONObject(i);
con.ConsignmentID = cObj.getInt("ConsignmentID");
con.ConsignmentCreationDate = cObj.getString("ConsignmentCreationDate");
con.ConsignmentCustRef = cObj.getString("ConsignmentCustRef");
con.OrderNo = cObj.getString("OrderNo");
con.ConsignmentActive = cObj.getBoolean("ConsignmentActive");
con.JobType = cObj.getString("JobType");
//Client object
JSONObject clObj = cObj.getJSONObject("Client");
Clients cl = new Clients();
cl.ClientId = clObj.getInt("ClientID");
cl.ClientName = clObj.getString("ClientName");
con.Clients = cl;
//ShipTo object
JSONObject stObj = cObj.getJSONObject("ShipTo");
ShipTo sto = new ShipTo();
sto.ShipToId = stObj.getInt("ShipToId");
sto.ShipToName = stObj.getString("ShipToName");
sto.ShipToAddress1 = stObj.getString("ShipToAddress1");
sto.ShipToAddress2 = stObj.getString("ShipToAddress2");
sto.ShipToCity = stObj.getString("ShipToCity");
sto.ShipToPostcode = stObj.getString("ShipToPCode");
sto.ShipToState = stObj.getString("ShipToState");
con.ShipTo = sto;
//FreightZone object
JSONObject fzObj = cObj.getJSONObject("FreightZone");
FreightZones fz = new FreightZones();
fz.FreightZoneID = fzObj.getInt("FreightZoneId");
fz.FreightZone = fzObj.getString("FreightZone");
con.FreightZone = fz;
JSONArray conItems = cObj.getJSONArray("ConsignmentItems");
for(int m = 0; m < conItems.length(); m++)
{
JSONObject cit = conItems.getJSONObject(m);
ConsignmentItems ci = new ConsignmentItems();
ci.ConsignmentItemID = cit.getInt("ConsignmentItemsID");
ci.Quantity = cit.getInt("QTY");
//get Product from ConsignmentItems
JSONObject pro = cit.getJSONObject("Products");
Products prod = new Products();
prod.ProductId = pro.getInt("ProductID");
prod.ProductModel = pro.getString("ProductModel");
prod.ItemsPerCarton = pro.getInt("PerCarton");
prod.ProductDescription = pro.getString("Description");
prod.Height = (float) pro.getDouble("Height");
prod.Length = (float) pro.getDouble("Length");
prod.Width = (float) pro.getDouble("Width");
prod.Cubic = (float) pro.getDouble("Cubic");
ci.Product = prod;
conItemList.add(ci);
con.ConsignmentItems = conItemList;
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
return con;
}
public void ShowItemsOfManifest(Consignments consignments)
{
Bundle bundle = new Bundle();
Intent newIntent = new Intent(this.getApplicationContext(), ConActivity.class);
newIntent.putExtras(bundle);
newIntent.putExtra("Consignment", consignments);
this.startActivity(newIntent);
}
public void onSearchClick(View view)
{
new MyAsyncTask().execute();
ManifestItemAdapter mia = new ManifestItemAdapter(MainActivity.this, android.R.layout.simple_spinner_item, jobList);
list_job.setAdapter(mia);
}
}
I look forward to understanding more about ASyncTask through your constructive comments on my code. Thanks ahead for helping me improve my code and my understanding of Android, guys! :)
PS: Please let me know if you need any more code to work with. I will update my post with more information as necessary. Cheers!
The point behind AsyncTask is to allow you to run background work on a separate thread such as networking stuff so you don't hold up the UI and users can still do things while data is being downloaded.
Which of my code in the ASyncTask is the parameter that is being passed?
You currently are not passing any params to the AsyncTask
new MyAsyncTask().execute(); // you would put params in here if needed such as a URL, String, etc...
What is the progress value in my AsyncTask?
As far as I can tell, you don't have one. If you wanted to you could use publishProgress(value) and that would be sent to onProgressUpdate() to update things like files downloaded, time of progression, time left, etc...
Finally, is my return value the ArrayList of ManifestItems?
you are returning jobList so that is what will get sent to onPostExecute() to do what you need with it
Note: One of the most important things to understand about AsyncTask is that you can't update the UI from doInBackground() so you must do this in one of the other AsyncTask methods or pass values back to a UI function. Also, AsyncTask works differently in 2.3 than it does in 3.0 and beyond. They don't run in parallel any more but put into a queue. So you may want to read about executeOnExecutor() if you want them to run in parallel in 4.2. I hope this answers your questions
AsyncTask
executeOnExecutor()(http://developer.android.com/reference/android/os/AsyncTask.html#executeOnExecutor(java.util.concurrent.Executor, Params...)
A couple other things I see is that you will want to add the #Override annotation to the implemented methods as well as super calls.

How to fetch and split data of URL and set it to TextView in Android?

Actually I am trying to fetch data from a URL and have to split that data string using the split("#") method and have to set that data in TextView.
It's running without error, but it is showing nothing.
enter code here
package com.androidpeople.view;
import java.io.BufferedReader;
import java.io.IOException;``
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class WebViewExample extends Activity {
String element1,element2,element3,element4,element5,element6;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView text1=(TextView) findViewById(R.id.textView1);
TextView text2=(TextView) findViewById(R.id.textView2);
TextView text3=(TextView) findViewById(R.id.textView3);
TextView text4=(TextView) findViewById(R.id.textView4);
TextView text5=(TextView) findViewById(R.id.textView5);
TextView text6=(TextView) findViewById(R.id.textView6);
String nextLine;
URL url = null;
URLConnection urlConn = null;
InputStreamReader inStream = null;
BufferedReader buff = null;
// Create the URL obect that points
// at the default file index.html
if (nextLine !=null){
String aColors[] = nextLine.split("#");
element1= aColors[0];
element2= aColors[1];
element3= aColors[2];
element4= aColors[3];
element5= aColors[4];
element6= aColors[5];
}
}
}
catch(IOException e){
e.printStackTrace();
}
text1.setText("text is" +element1);
text2.setText("text is" +element2);
text3.setText("text is" +element3);
text4.setText("text is" +element4);
text5.setText("text is" +element5);
text6.setText("text is" +element6);
}
}
I think Split method have to use like this :
String aColors[] = nextLine.split("\\#");
instead of
String aColors[] = nextLine.split("#");
Hope it helps.

setOnClickListener - application stopped unexpectedly

As soon as I use setOnClickListener for a button in my code, when I start the application it says the application has stopped unexpectedly
package example.khumbayatabbed;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class Category extends ListActivity{
int categ=0;
String[] categories = new String[100];
Button button1;
EditText edittext1;
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
edittext1= (EditText) findViewById(R.id.edittext);
button1 = (Button) findViewById(R.id.button);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
edittext1.setText("");
Toast.makeText(getApplicationContext(), "Hello",
Toast.LENGTH_SHORT).show();
}
});
// setContentView(R.layout.main);
// Create a crude view - this should really be set via the layout resources
// but since its an example saves declaring them in the XML.
// Set the text and call the connect function.
//call the method to run the data retreival
final String KEY_121 = "http://myurl";
getServerData(KEY_121);
if(mylist.isEmpty())
Toast.makeText(getApplicationContext(), "No more sub categories",
Toast.LENGTH_SHORT).show();
else
display(mylist);
}
private void getServerData(String jason) {
mylist = new ArrayList<HashMap<String, String>>();
InputStream is = null;
String returnString="";
String result = "";
//mylist.clear();
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(jason);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","url: "+json_data.getString("url")+
", name: "+json_data.getString("value")
);
//Get an output to the screen
categories[categ++]=json_data.getString("value");
map.put("name", json_data.getString("value"));
map.put("url", json_data.getString("url"));
mylist.add(map);
returnString += jArray.getJSONObject(i).getString("url") + "\n";
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
private void display(ArrayList<HashMap<String, String>> list)
{
ListAdapter adapter=new SimpleAdapter(this,list,R.layout.list_item2, new String[] {"name"}, new int[]{R.id.cat_name});
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
#SuppressWarnings("unchecked")
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
HashMap<String, String> tmp = new HashMap<String, String>();
tmp=(HashMap<String, String>)parent.getItemAtPosition(position);
String cat_url=tmp.get("url");
final String KEY_121 = "http://myurl/"+cat_url;
getServerData(KEY_121);
if(mylist.isEmpty())
Toast.makeText(getApplicationContext(), "No more sub categories",
Toast.LENGTH_SHORT).show();
else
display(mylist);
}
});
}
}
This is code for my main page:
public class Khumbayatabbed extends TabActivity
{ /** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Resources res = getResources(); // Resource object to get Drawables
TabHost tabHost = getTabHost(); // The activity TabHost
TabHost.TabSpec spec; // Reusable TabSpec for each tab
Intent intent; // Reusable Intent for each tab
// Create an Intent to launch an Activity for the tab (to be reused)
intent = new Intent().setClass(this, Category.class);
// Initialize a TabSpec for each tab and add it to the TabHost
spec = tabHost.newTabSpec("category").setIndicator("Category",
res.getDrawable(R.drawable.ic_tab))
.setContent(intent);
tabHost.addTab(spec);
// Do the same for the other tabs
intent = new Intent().setClass(this, Event.class);
spec = tabHost.newTabSpec("event").setIndicator("Event",
res.getDrawable(R.drawable.ic_tab))
.setContent(intent);
tabHost.addTab(spec);
tabHost.setCurrentTab(0);
}
}
The main.xml looks like this:
You didn't wrtie setContentView for your layout.So you can't access Your editText1 and same for the button1.
write something like
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
In your Main Page to call this use
Intent myIntent = new Intent(MainPage.this,Category.class);
MainPage.this.startActivity(myIntent);

Categories

Resources