I'm new to android and i would like to create an application that reads data from mysql server. I've taken from web an example about this, but i cannot make it work
I'm using eclipse for this and for the other part, php and mysql.
First of all, here is my php script that is running ok (city.php):
<?php
//connecting to database
$sql=mysql_query("select * from city");
$output = array();
while(list($id,$name)=mysql_fetch_array($sql)){
$output[$id]=$name;
}
print(json_encode($output));
mysql_free_result($sql);
?>
This is returning:
{"1":"Brasov","2":"Bucuresti"}
On my android project from eclipse, I have in the MainActivity.java:
package com.example.mycity;
import android.os.Bundle;
import android.app.Activity;
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.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.net.ParseException;
import android.util.Log;
import android.widget.Toast;
public class MainActivity extends Activity {
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.steagu.ro/android/city.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() != 200) {
Log.d("MyApp", "Server encountered an error.");
}
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
//e.printStackTrace();
Log.e("log_tag", "Error in http connection: "+e.toString());
}
}
}
But when I'm running this, I receive an error on logcat:it's not connecting to the file:Error in http connection: android.os.NetworkOnMainThreadException
10-24 13:04:34.429: I/dalvikvm(982): threadid=3: reacting to signal 3
10-24 13:04:34.649: I/dalvikvm(982): Wrote stack traces to '/data/anr/traces.txt'
10-24 13:04:34.859: E/log_tag(982): Error in http connection: android.os.NetworkOnMainThreadException
10-24 13:04:34.919: I/dalvikvm(982): threadid=3: reacting to signal 3
10-24 13:04:34.949: I/dalvikvm(982): Wrote stack traces to '/data/anr/traces.txt'
10-24 13:04:35.151: D/gralloc_goldfish(982): Emulator without GPU emulation detected.
10-24 13:04:35.479: I/dalvikvm(982): threadid=3: reacting to signal 3
10-24 13:04:35.499: I/dalvikvm(982): Wrote stack traces to '/data/anr/traces.txt'
I have permission for internet in the AndroidManifest.xml:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mycity"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I don't know where is the problem. Can anybody help me with this? Thank you!
You may use an AsyncTask class to carry out your network operations as strictmode does not allow it to be done on the main UI example as follows
public class MainActivity extends Activity {
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new httpRequest().execute();
}
private class httprRequest extends AsyncTask<String, Integer, String>{
#override
public String doInBackground(String.... params){
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.steagu.ro/android/city.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() != 200) {
Log.d("MyApp", "Server encountered an error.");
}
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
//e.printStackTrace();
Log.e("log_tag", "Error in http connection: "+e.toString());
}
}
}
}
}
The problem is this:
10-24 13:04:34.859: E/log_tag(982): Error in http connection:
android.os.NetworkOnMainThreadException
You need to do your network access on a different thread.
Thank you kabuto178, I'm made the changes and it's connecting. I've wrote the code also for retrieving data from mysql, so who need this, can use my example
Here is the code:
package com.example.mycity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
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.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.net.ParseException;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
String result = "";
InputStream is = null;
StringBuilder sb=null;
//String ct_name = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new httprRequest().execute();
int ct_id=0;
String ct_name="";
//Toast.makeText(getBaseContext(), "This is "+result, 3000).show();
try {
Thread.sleep(1000L);
} catch (Exception te) {}
try{
//ct_name = result;
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data= jArray.getJSONObject(i);
ct_id=json_data.getInt("CITY_ID");
ct_name += json_data.getString("CITY_NAME")+":";
}
}
catch(JSONException e1){
e1.printStackTrace();
} catch (ParseException e1) {
e1.printStackTrace();
}
TextView tv1 = (TextView) findViewById(R.id.textView1);
tv1.setText(ct_name);
}
private class httprRequest extends AsyncTask<String, Integer, String>{
#Override
public String doInBackground(String... params){
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.steagu.ro/android/city.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() != 200) {
Log.d("MyApp", "Server encountered an error.");
}
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
//e.printStackTrace();
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);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
//Toast.makeText(getBaseContext(), "Am eroare aici", 3000).show();
Log.e("log_tag", "Error converting result "+e.toString());
}
/*
Toast.makeText(getBaseContext(), "Here i am", 3000).show();
*/
return result;
}
}
}
I have to change a little bit the code, cause i put a thread.sleep. Instead of it, i have to check if i have a value into result (in a while loop). I think this is happening because at that moment when i try to parse the value, i don;t have a value in result.
The php code is:
<?php
//connecting to database
$sql=mysql_query("select * from city where CITY_NAME like '%'");
$output = array();
while($row=mysql_fetch_assoc($sql)){
$output[]=$row;
}
echo json_encode($output);
mysql_free_result($sql);
?>
Table 'city' has two columns, CITY_ID and CITY_NAME.
Related
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.StrictMode;
import android.widget.TextView;
import java.io.File;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.OkHttpClient;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
final TextView textView = findViewById(R.id.text_view_id);
final String IMAGE1 = "storage/emulated/0/Download/image_1.jpeg";
File file1 = new File(IMAGE1);
try {
final MediaType MEDIA_TYPE_JPEG = MediaType.parse("image/jpeg");
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("images", "image_1.jpeg",
RequestBody.create(file1, MEDIA_TYPE_JPEG))
.addFormDataPart("organs", "flower")
.build();
Request request = new Request.Builder()
.url("https://my-api.plantnet.org/v2/identify/all?api-key=123")
.post(requestBody)
.build();
OkHttpClient client = new OkHttpClient();
Response response = client.newCall(request).execute();
textView.setText(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
}
I understand that I'm trying to run a network activity here on the main thread. That's why I included the StrictMode permitAll thing to get around the issue (I saw an answer to a similar topic that suggested doing so). I am trying to use the PlantNet API here and I use my phone for testing. The same phone where the image is saved.
go see retrofit
it provides a nice and easy way to make your network calls off the main thread
package com.example.fyptrialapp;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
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.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class SearchByName extends Activity{
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
InputStream inputStream=null;
Intent i;
//public static final String recipes[]=new String[]{"Almond-Sheera","Bhel","Bread-Pizzas","Carrot-Pickle","Carrot-Relish"};
String recipes[];
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.search_recipe);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Button b2=(Button)findViewById(R.id.bSearchByName);
try{
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://10.0.2.2/fypTrial2/searchByName.php");
response = httpclient.execute(httppost); // Execute HTTP Post Request
inputStream = response.getEntity().getContent();
String result=null;
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line=null;
while((line=reader.readLine())!= null){
sb.append(line+"\n");
}
inputStream.close();
result=sb.toString();
JSONArray jArray=new JSONArray(result);// this statment gives error
for(int i=0;i<jArray.length();i++){
JSONObject json=jArray.getJSONObject(i);
recipes[i]=json.getString("name");
}
}
catch(Exception e){
Log.e("log_tag3", "Error convering result"+e.toString());
}
ArrayAdapter<String> ac=new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,recipes);
AutoCompleteTextView tv=(AutoCompleteTextView) findViewById(R.id.autoCompleteTextView2);
tv.setAdapter(ac);
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent("com.example.practice.Search_Result");
startActivity(i);
}
});
}
}
ERROR
java.nullpointerexception. Error converting result variable.And the
fatal main error
If i want to use ASnk task how should i write it.
JSON syntax never starts as an array. It could be that it starts with { followed by [, but never straight to [. This is why trying to convert your results to JSONArray will not work. You should therefor try to get the object first, then the array elements.
JSONObject jo = new JSONObject(result);
JSONArray jArray = jo.getJSONArray("keyIdentifyer");
If you dont have the array key identifyer, you could try to iterate or get the first element. See this post answear on iterations when no keys are present.
You should indeed use AsyncTask for the networking part. Your app probably already crashes with a NetworkOnMainThread error follow this link for the usasge of AsyncTask.
But that besides, you are providing to little code to point to a reason for the NullPointerException. You should always check if an object is not null if it may occur it is.
try{
//your code
}catch(NullPointerException ex){
ex.printStackTrace();
}
I am creating a application which gets the input from edit text and sends a mail acording to the information.I am using Http post to do this i want to communicate with the Php script to send the mail please have a look at my code..
Php script
<?php
$name = $_POST['name'];
$to = $_POST['to'];
$from = $_POST['from'];
$subject = $_POST['subject'];
$message = "From: ".$name."\r\n";
$message .= $_POST['message'];
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
?>
my Activity:
package dolphin.developers.com;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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.protocol.HTTP;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import dolphin.devlopers.com.R;
public class misc1 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.eamilspoof);
EditText textw =(EditText) findViewById(R.id.editText1);
final String strd = textw.getText().toString();
EditText textw3 =(EditText) findViewById(R.id.editText2);
final String strd3 = textw3.getText().toString();
EditText textw3d =(EditText) findViewById(R.id.editText3d);
final String strd3d = textw3d.getText().toString();
EditText textw3dd =(EditText) findViewById(R.id.editText3);
final String name = textw3d.getText().toString();
EditText textw3df =(EditText) findViewById(R.id.editText4);
final String subject = textw3d.getText().toString();
Button pds = (Button)findViewById(R.id.button1d);
pds.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String site = "www.dolphin123.net78.net/mailer.php";
String namer1 = name;
String to = strd;
String from = strd3;
String subject1 = subject;
String message = strd3d;
String content = "";
try
{
/* Sends data through a HTTP POST request */
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(site);
List <NameValuePair> params = new ArrayList <NameValuePair> ();
params.add(new BasicNameValuePair("name", namer1));
params.add(new BasicNameValuePair("to", to));
params.add(new BasicNameValuePair("from", from));
params.add(new BasicNameValuePair("subject", subject1));
params.add(new BasicNameValuePair("message", message));
httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
/* Reads the server response */
HttpResponse response = httpClient.execute(httpPost);
InputStream in = response.getEntity().getContent();
StringBuffer sb = new StringBuffer();
int chr;
while ((chr = in.read()) != -1)
{
sb.append((char) chr);
}
content = sb.toString();
in.close();
/* If there is a response, display it */
if (!content.equals(""))
{
Log.i("HTTP Response", content);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
};
}
}
Logcat :
08-10 17:55:20.405: W/System.err(12988): java.lang.IllegalStateException: Target host must not be null, or set in parameters. scheme=null, host=null, path=www.dolphin123.net78.net/mailer.php
08-10 17:55:20.405: W/System.err(12988): at org.apache.http.impl.client.DefaultRequestDirector.determineRoute(DefaultRequestDirector.java:591)
08-10 17:55:20.405: W/System.err(12988): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:293)
08-10 17:55:20.405: W/System.err(12988): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:670)
08-10 17:55:20.405: W/System.err(12988): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:509)
08-10 17:55:20.410: W/System.err(12988): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
08-10 17:55:20.410: W/System.err(12988): at dolphin.developers.com.misc1$1.onClick(misc1.java:87)
08-10 17:55:20.410: W/System.err(12988): at android.view.View.performClick(View.java:4211)
08-10 17:55:20.410: W/System.err(12988): at android.view.View$PerformClick.run(View.java:17267)
08-10 17:55:20.410: W/System.err(12988): at android.os.Handler.handleCallback(Handler.java:615)
08-10 17:55:20.410: W/System.err(12988): at android.os.Handler.dispatchMessage(Handler.java:92)
new Log:
08-05 13:08:17.365: D/SntpClient(73): request time failed: java.net.SocketException: Address family not supported by protocol
Prepend the protocol to the String representation of your URI.
So it should be: "http://www.dolphin123.net78.net/mailer.php"
You can your url with above url with prepend http://
Hi I am trying to make an android widget. In this widget i am trying to update the value of my text view by calling a web service and getting the data from it and displaying it in the text view after a particular tie interval and i am getting an exception.
Exception:java.lang.RuntimeException: Unable to start service com.example.newwidget.UpdateService#40ce9518withIntent{cmp=com.example.newwidget
/.UpdateService (has extras) }: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
Here is the code which i have tried,
Widget.java
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;
import android.widget.RemoteViews.RemoteView;
import android.widget.Toast;
public class Widget extends AppWidgetProvider {
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
Toast.makeText(context, "OnUpdate", Toast.LENGTH_LONG).show();
ComponentName thisWidget = new ComponentName(context,
Widget.class);
int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
Toast.makeText(context, "allWidgetIds", Toast.LENGTH_LONG).show();
// Build the intent to call the service
Intent intent = new Intent(context.getApplicationContext(),
UpdateService.class);
Toast.makeText(context, "call UpdateService", Toast.LENGTH_LONG).show();
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, allWidgetIds);
Toast.makeText(context, "", Toast.LENGTH_LONG).show();
// Update the widgets via the service
context.startService(intent);
}
}
UpdateService.java
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.ProgressDialog;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;
public class UpdateWidget extends Service {
private RemoteViews views;
private String url;
private String strAPIRender;
private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private ProgressDialog Dialog = new ProgressDialog(null);
private HttpResponse response;
private HttpEntity httpEntity;
#Override
public void onStart(Intent intent, int startId) {
Log.d("AppWidget.UpdateService", "onStart()");
Toast.makeText(UpdateWidget.this, "Onstart", Toast.LENGTH_LONG).show();
// Build the widget update for today
Toast.makeText(UpdateWidget.this, "Updateviews", Toast.LENGTH_LONG).show();
RemoteViews updateViews = buildUpdate(this);
Log.d("WordWidget.UpdateService", "update built");
Toast.makeText(UpdateWidget.this, "buildupdate finish", Toast.LENGTH_LONG).show();
// Push update for this widget to the home screen
ComponentName thisWidget = new ComponentName(this, WidgetAppActivity.class);
AppWidgetManager manager = AppWidgetManager.getInstance(this);
Toast.makeText(UpdateWidget.this, "final update", Toast.LENGTH_LONG).show();
manager.updateAppWidget(thisWidget, updateViews);
Log.d("WordWidget.UpdateService", "widget updated");
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
public RemoteViews buildUpdate(Context context) {
// Pick out month names from resources
Toast.makeText(UpdateWidget.this, "buildupdate", Toast.LENGTH_LONG).show();
url = "http://www.webservicex.net/currencyconvertor.asmx/ConversionRate?FromCurrency=USD&ToCurrency=INR";
grabURL(url);
Toast.makeText(UpdateWidget.this, "grabURL finish", Toast.LENGTH_LONG).show();
String result = strAPIRender;
views = new RemoteViews(context.getPackageName(), R.layout.activity_widget_app);
views.setTextViewText(R.id.update, result);
return views;
}
public void grabURL(String url) {
Toast.makeText(UpdateWidget.this, "in grabURL method", Toast.LENGTH_LONG).show();
Toast.makeText(null, "execute url", Toast.LENGTH_LONG).show();
try {
HttpGet httpget = new HttpGet(url);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
Content = Client.execute(httpget, responseHandler);
} catch (ClientProtocolException e) {
Error = e.getMessage();
//cancel(true);
} catch (IOException e) {
Error = e.getMessage();
//cancel(true);
}
parseXml(Content);
}
public String parseXml(String content) {
try {
System.out.println(content);
try {
strAPIRender = XMLHandler.GetTagValue("double",content);
} catch (Exception e) {
System.out.println(" catch b");
}
} catch (Exception e) {
System.out.println(" exception in parseXML");
}
return strAPIRender;
}
}
Manifest file
<uses-sdk android:minSdkVersion="8" />
<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" >
<receiver
android:name=".Widget"
android:icon="#drawable/ic_launcher"
android:label="A Widget" >
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="#xml/widget_info" />
</receiver>
<service android:name="com.example.newwidget.UpdateService"></service>
</application>
Remove the following line from UpdateService:
private ProgressDialog Dialog = new ProgressDialog(null);
That "Dialog" doesn't appear (at quick glance of that class) to be used anywhere. If you do intend to use it you can't instantiate it like that (it needs a real Context). That should resolve the specific error you are asking about.
(Even if you fix that error, I'm not sure this code will work as expected. You might also want to consider, just for starters: remove all the toasts for debug purposes and use logging and logcat, and/or a debugger; don't use the main UI thread (which services also use by default) for network I/O (see IntentService for an easy way around that); don't do dialogs/alerts/toasts from a Service; and watch out for non-standard naming conventions like starting member variables in upper case, that makes the code difficult to follow (especially when it's not consistent, even if it doesn't follow the convention).)
I'm sure I have just structured my code wrong or something but I have been looking at it soo long I can see it.
I have managed to get a class working to access my database and bring back data, but when I try to build this class into my tab widget it doesn't seem to work.
This is were I call the class:
// Create an Intent to launch an Activity for the tab (to be reused)
intent = new Intent().setClass(this, recipelist.class);
// Initialize a TabSpec for each tab and add it to the TabHost
spec = tabHost.newTabSpec("recipe").setIndicator("recipe", res.getDrawable(R.drawable.ic_tab_list)).setContent(intent);
tabHost.addTab(spec);
and this is the class with the database code:
package fridge.mate;
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.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.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.TextView;
public class recipelist extends Activity {
TextView txt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
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.
LinearLayout rootLayout = new LinearLayout(getApplicationContext());
txt = new TextView(getApplicationContext());
rootLayout.addView(txt);
setContentView(rootLayout);
// Set the text and call the connect function.
txt.setText("Connecting...");
//call the method to run the data retreival
txt.setText("gfgfgf...");
}
public static final String KEY_121 = "http://www.bankruptcy.co.uk/1.php"; //i use my real ip here
private String getServerData(String returnString) {
InputStream is = null;
String result = "";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name","beans"));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(KEY_121);
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++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","ID: "+json_data.getInt("ID")+
", name: "+json_data.getString("name")+
", servings: "+json_data.getString("servings")+
", discription: "+json_data.getString("discription")
);
//Get an output to the screen
returnString += "\n\t" + jArray.getJSONObject(i);
txt.setText("Connecting...");
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return returnString;
}
}
Few notes:
You are calling setContentView() twice. One is enough. So which one is the right one?
You are calling new LinearLayout(getApplicationContext()). Activity is a Context, so you can call new LinearLayout(this). Same for TextView.
I don't see any Tabs. Where are they? I only see LinearLayout and TextView inside it.
You should not perform long-running task in UI thread (EDT). Use AsyncTask for this.
Take a look at Tabs example to see how they did it.