I'm trying to access the web service defined in WSDL from Android activity. The expected output is json formatted string.
At the first step my aim is to print this string to a text view in Android. So I used following code :
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
private final String NAMESPACE = "XXXXXXXXXXXXXXX";
private final String URL = "XXXXXXXXXXXXXXXXX";
private final String SOAP_ACTION = "XXXXXXXXXXXX";
private final String METHOD_NAME = "XXXXXXXXXXXXXXXXX";
private String webResponse = "";
private TextView textView;
private Thread thread;
private Handler handler = new Handler();
/** Called when the activity is first created. */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView1);
startWebAccess();
}
public void startWebAccess() {
thread = new Thread() {
public void run() {
try {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(
URL);
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive response = (SoapPrimitive) envelope
.getResponse();
webResponse = response.toString();
Log.d("TAG", webResponse);
}
catch (Exception e) {
e.printStackTrace();
}
handler.post(createUI);
}
};
thread.start();
}
final Runnable createUI = new Runnable() {
public void run() {
Log.d("TAG", webResponse);
textView.setText(webResponse);
}
};
#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, menu);
return true;
}
}
But when I'm trying to run the code I can see following error in log cat (And no output in Text view):
java.lang.ClassCastException: java.util.Vector
Here is the complete log cat out put :
08-06 09:57:11.792: D/dalvikvm(953): GC_FOR_MALLOC freed 771 objects / 322464 bytes in 130ms
08-06 09:57:13.252: D/dalvikvm(953): GC_FOR_MALLOC freed 3182 objects / 473904 bytes in 41ms
08-06 09:57:13.252: D/NativeCrypto(953): Freeing OpenSSL session
08-06 09:57:13.293: W/System.err(953): java.lang.ClassCastException: java.util.Vector
08-06 09:57:13.293: W/System.err(953): at org.sahana.peoplelocator.MainActivity$2.run(MainActivity.java:56)
What can be the error ? please help me I'm stuck here.
Thank you in advance!
Try the below
Replace this
SoapPrimitive response = (SoapPrimitive) envelope
.getResponse();
By
SoapObject response=(SoapObject) envelope.bodyIn;
I tried your code this is the result i got
ClassCastException is thrown when you try to cast invalid types. For example, let's say you have an ArrayList v. If you do String s=(String)v, it will throw an exception because you can't convert an ArrayList to a String. In this case, the only casting you're doing is SoapPrimitive response = (SoapPrimitive) envelope
.getResponse(); Which means that envelope.getResponse() does not return a SoapPrimitive. It probably returns a java.util.Vector, based on the error message.
I've never used whatever libraries you're using, so I can't give you a definite answer. However, envelope.getResponse() ClassCastException on google gives me a lot of results. Try that, and good luck!
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
MainActivity.java
package com.example.yashpachisia.fetchjson;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends ActionBarActivity {
String myJSON;
private static final String TAG_RESULTS="result";
private static final String TAG_NAME = "name";
private static final String TAG_AGE = "age";
private static final String TAG_SEX ="sex";
JSONArray peoples = null;
ArrayList<HashMap<String, String>> personList;
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.listView);
personList = new ArrayList<HashMap<String,String>>();
getData();
}
protected void showList(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
peoples = jsonObj.getJSONArray(TAG_RESULTS);
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String name = c.getString(TAG_NAME);
String age = c.getString(TAG_AGE);
String sex = c.getString(TAG_SEX);
HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_NAME,name);
persons.put(TAG_AGE,age);
persons.put(TAG_SEX,sex);
personList.add(persons);
}
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, personList, R.layout.list_item,
new String[]{TAG_NAME,TAG_AGE,TAG_SEX},
new int[]{R.id.name, R.id.age, R.id.sex}
);
list.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://localhost/test/form.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON=result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
#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, menu);
return true;
}
/* #Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_user) {
return true;
}
return super.onOptionsItemSelected(item);
}*/
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.yashpachisia.fetchjson">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Logcat window
12-19 17:17:59.353 5132-5132/? D/OpenGLRenderer: Enabling debug mode 0
12-19 17:17:59.353 5132-5132/? D/AndroidRuntime: Shutting down VM
12-19 17:17:59.357 5132-5132/? W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0xa6299288)
12-19 17:17:59.357 5132-5132/? E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
at org.json.JSONTokener.nextValue(JSONTokener.java:94)
at org.json.JSONObject.<init>(JSONObject.java:154)
at org.json.JSONObject.<init>(JSONObject.java:171)
at com.example.yashpachisia.fetchjson.MainActivity.showList(MainActivity.java:56)
at com.example.yashpachisia.fetchjson.MainActivity$1GetDataJSON.onPostExecute(MainActivity.java:128)
at com.example.yashpachisia.fetchjson.MainActivity$1GetDataJSON.onPostExecute(MainActivity.java:89)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
call this method showList() only after checking the result you get in onPostExecute() is not null or empty
if(result != null && result.length >0 ){
myJSON=result;
showList()
}
as your myJson could be empty you are trying to run Json code on it, due to which you are getting NulPointerError
Update
if you are getting the null value it means, that you are not getting the data from the web service or you are calling it wrong.
I saw some mistakes in your code so i wrote you a new one. my code uses commons-io-2.4.jar library but you can always write your own code to see the result
String chartString = "your url which you want to call";
URL chartURL = new URL(chartString);
HttpURLConnection chartHttpURLConnection = (HttpURLConnection) chartURL.openConnection();
chartHttpURLConnection.connect();
String result = IOUtils.toString(chartHttpURLConnection.getInputStream());
System.out.println(""+result);
as you are trying to call the local serve though emulator so the IP address would be 10.0.2.2
so your URL which you would be calling is
URL url = new URL(http://10.0.2.2/test/form.php);
have a look at this IP Address for the Emulator
i am using a reference code for testing ,but when i run the app and click the submit button it shows "Unfortunately your app has Stopped".
Here is my java.class
package com.internship.mtslogin;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class fpasswd extends Activity implements OnClickListener{
private EditText email ;
private Button msubmit;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
//php login script
//localhost :
//testing on your device
//put your local ip instead, on windows, run CMD > ipconfig
//or in mac's terminal type ifconfig and look for the ip under en0 or en1
private static final String LOGIN_URL ="http://xxx.xxx.x.x:1234/webservice/register.php";
//testing from a real server:
//private static final String LOGIN_URL = "http://www.yourdomain.com/webservice/register.php";
//ids
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forgot_passwd);
email = (EditText)findViewById(R.id.email);
msubmit = (Button)findViewById(R.id.submit);
msubmit.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new CreateUser().execute();
}
class CreateUser extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(fpasswd.this);
pDialog.setMessage("Please wait, Registering");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String emailid = email.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", emailid));
Log.d("request!", "starting");
//Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// full json response
Log.d("Login attempt", json.toString());
// json success element
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("User Created!", json.toString());
finish();
return json.getString(TAG_MESSAGE);
}else{
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(fpasswd.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
But when i run it in a localhost it works fine.
the parameters to be send is only "email".
and url in which i am doing is real server.
i have removed the real url and put a dummy url for string passing.
Can anyone tell me what is going wrong?
here is the logcat details.
FATAL EXCEPTION: AsyncTask #3
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
at java.util.concurrent.FutureTask.run(FutureTask.java:239)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.SecurityException: Permission denied (missing INTERNET permission?)
at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
The answer is in the error message. You are missing INTERNET permission. Add to your manifest:
<uses-permission android:name="android.permission.INTERNET"/>
well it looks like you dont have access to the internet.
Caused by: java.lang.SecurityException: Permission denied (missing INTERNET permission?)
Add this line to the AndroidMainfest.xml to enable the Internet access.
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
I am trying to do a very simple POST from an android application to a php script that will update a database. Unfortunately, this is giving me a debugger error (eclipse) on line 52. Below is the code:
package com.example.testhttppost;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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 android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#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, menu);
return true;
}
public void updateDiscountTable(View view)
{
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.test.com/jsonpost.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("shop", "ZARA"));
nameValuePairs.add(new BasicNameValuePair("discount", "20%"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost); //Line 52
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
and the PHP script is:
<?php
// PHP variable to store the host address
$db_host = "localhost";
// PHP variable to store the username
$db_uid = "dsdsdsv_android";
// PHP variable to store the password
$db_pass = "test1234";
// PHP variable to store the Database name
$db_name = "dsdsdsv_android";
// PHP variable to store the result of the PHP function 'mysql_connect()' which establishes the PHP & MySQL connection
$db_con = mysql_connect($db_host,$db_uid,$db_pass) or die('could not connect');
mysql_select_db($db_name);
$shopId = $_POST['id'];
$shopName = $_POST['shop'];
$discount = $_POST['discount'];
mysql_query("insert into discounts(id, shop, discount) values ($shopId, $shopName, $discount)");
// mysql_query("insert into discounts(id, shop, discount)values(121, 'sadsdas','dasdasdsa')");
?>
The interface of the application is nothing but a button. This button is linked with the method above defined updateDiscountTable. Thanks and looking forward to replies.
You are performing networking operations on the main application thread probably. You need to move this to a background thread. You can use Asynctask.
You need to Keep your app responsive.
I'm trying to automatically get a URL from my database table online when I click on the button btnDelete. The problem is that it returns the correct values from the database but when try to put it with:
Uri uri = Uri.parse(TAG_url);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
It says that "unfortunately, access to database has stopped."
When I make a Log.d() from the TAG_url it returns only "URL" but when I use
txtDesc.setText(product.getString(TAG_url));
it displays correctly the link from the database.
03-14 11:50:18.169: E/Trace(5227): error opening trace file: No such file or directory (2)
03-14 11:50:31.499: E/AndroidRuntime(5227): FATAL EXCEPTION: main
03-14 11:50:31.499: E/AndroidRuntime(5227): java.lang.NullPointerException: uriString
03-14 11:50:31.499: E/AndroidRuntime(5227): at android.net.Uri$StringUri.<init>(Uri.java:464)
03-14 11:50:31.499: E/AndroidRuntime(5227): at android.net.Uri$StringUri.<init>(Uri.java:454)
03-14 11:50:31.499: E/AndroidRuntime(5227): at android.net.Uri.parse(Uri.java:426)
03-14 11:50:31.499: E/AndroidRuntime(5227): at com.example.androidhive.EditProductActivity1$2.onClick(EditProductActivity1.java:106)
03-14 11:50:31.499: E/AndroidRuntime(5227): at android.view.View.performClick(View.java:4084)
03-14 11:50:31.499: E/AndroidRuntime(5227): at android.view.View$PerformClick.run(View.java:16966)
03-14 11:50:31.499: E/AndroidRuntime(5227): at android.os.Handler.handleCallback(Handler.java:615)
03-14 11:50:31.499: E/AndroidRuntime(5227): at android.os.Handler.dispatchMessage(Handler.java:92)
03-14 11:50:31.499: E/AndroidRuntime(5227): at android.os.Looper.loop(Looper.java:137)
03-14 11:50:31.499: E/AndroidRuntime(5227): at android.app.ActivityThread.main(ActivityThread.java:4745)
03-14 11:50:31.499: E/AndroidRuntime(5227): at java.lang.reflect.Method.invokeNative(Native Method)
03-14 11:50:31.499: E/AndroidRuntime(5227): at java.lang.reflect.Method.invoke(Method.java:511)
03-14 11:50:31.499: E/AndroidRuntime(5227): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
03-14 11:50:31.499: E/AndroidRuntime(5227): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-14 11:50:31.499: E/AndroidRuntime(5227): at dalvik.system.NativeStart.main(Native Method)
03-14 11:50:44.299: E/Trace(5251): error opening trace file: No such file or directory (2)
Can anybody help me please?
package com.example.androidhive;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class EditProductActivity extends Activity {
EditText txtName;
EditText txtPrice;
EditText txtDesc;
EditText txtimg;
EditText txtCreatedAt;
Button btnSave;
Button btnDelete;
Button btnvideo;
String pid;
String url;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// single product url
private static final String url_product_detials = "http://10.0.2.2/android_connect/get_product_details.php";
// url to update product
private static final String url_update_product = "http://10.0.2.2/android_connect/update_product.php";
// url to delete product
private static final String url_delete_product = "http://10.0.2.2/android_connect/delete_product.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCT = "product";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_PRICE = "price";
private static final String TAG_DESCRIPTION = "description";
private static final String TAG_img = "img";
private static final String TAG_url = "url";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_product);
// save button
btnSave = (Button) findViewById(R.id.btnSave);
btnDelete = (Button) findViewById(R.id.btnDelete);
// getting product details from intent
Intent i = getIntent();
// getting product id (pid) from intent
pid = i.getStringExtra(TAG_PID);
// Getting complete product details in background thread
new GetProductDetails().execute();
// save button click event
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// starting background task to update product
new SaveProductDetails().execute();
}
});
// Delete button click event
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// deleting product in background thread
Log.v(TAG_url, "index=");
Uri uri = Uri.parse(TAG_url);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
}
/**
* Background Async Task to Get complete product details
* */
class GetProductDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EditProductActivity.this);
pDialog.setMessage("Loading movies details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting product details in background thread
* */
protected String doInBackground(String... params) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("pid", pid));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_product_detials, "GET", params);
// check your log for json response
Log.d("Single Product Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received product details
JSONArray productObj = json
.getJSONArray(TAG_PRODUCT); // JSON Array
// get first product object from JSON Array
JSONObject product = productObj.getJSONObject(0);
// product with this pid found
// Edit Text
url = TAG_url;
Log.v(url, "index=");
txtName = (EditText) findViewById(R.id.inputName);
txtPrice = (EditText) findViewById(R.id.inputPrice);
txtDesc = (EditText) findViewById(R.id.inputDesc);
// txtimg = (EditText) findViewById(R.id.inputimg);
// display product data in EditText
txtName.setText(product.getString(TAG_NAME));
txtPrice.setText(product.getString(TAG_PRICE));
txtDesc.setText(product.getString(TAG_url));
txtimg.setText(product.getString(TAG_img));
} else {
// product with pid not found
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private String getText(String string) {
// TODO Auto-generated method stub
return null;
}
});
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
pDialog.dismiss();
}
}
/**
* Background Async Task to Save product Details
* */
class SaveProductDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EditProductActivity.this);
pDialog.setMessage("Saving product ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Saving product
* */
protected String doInBackground(String... args) {
// getting updated data from EditTexts
String name = txtName.getText().toString();
String price = txtPrice.getText().toString();
String description = txtDesc.getText().toString();
String img = txtimg.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_PID, pid));
params.add(new BasicNameValuePair(TAG_NAME, name));
params.add(new BasicNameValuePair(TAG_PRICE, price));
params.add(new BasicNameValuePair(TAG_DESCRIPTION, description));
params.add(new BasicNameValuePair(TAG_img, img));
params.add(new BasicNameValuePair(TAG_url, url));
// sending modified data through http request
// Notice that update product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_update_product,
"POST", params);
// check json success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully updated
Intent i = getIntent();
// send result code 100 to notify about product update
setResult(100, i);
finish();
} else {
// failed to update product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product uupdated
pDialog.dismiss();
}
}
}
It looks to me that the var TAG_url is intended to be used only as a descriptor, not as a mutable object. First you have: private static final String TAG_url = "url"; defined as a node name. Using that for txtDesc.setText(product.getString(TAG_url)); works because you're retrieving the data associated with the node "url" (which is what TAG_url holds). In that instance, the data is not in the TAG_url var, but uses TAG_url as the key to find the data.
Any log reference to TAG_url will return it's contents: url. By the same token, a parse call using TAG_url will use it's contents as well. Therefore, Uri uri = Uri.parse(TAG_url); is actually calling Uri uri = Uri.parse("url"); - and so the error.
You should replace the TAG_url in the parse call with a var holding the actual url you intend to call. During your database call, you should store that url in a separate var, and parse it instead.
Edit:
Without knowing the structure of your JSON or other data, I can't say for certain. But as example, lets assume that the data returned from the database via the call product.getString(TAG_url) is the data you want sent to the parser. (I'm assuming that since you mentioned the data was correctly set to the TextView txtDesc when called via txtDesc.setText(product.getString(TAG_url));.)
Given that, you could create a field String incomingURL; at the top of the class, and assign the result of the database call like incomingURL = product.getString(TAG_url);. You would then set the TextView with the new field like txtDesc.setText(incomingURL);.
Then, use that variable for your parse: Uri uri = Uri.parse(incomingURL); That would take the data from the database call, and place it in the parser. Just keep in mind that you'll need to check for incomingURL being null if the button is clickable before the database call completes.
I am trying to do a simple insert from an Android application. I can run my php script from the browser by concatenating ?entry="Sample value from browser", but when I run the application from Android, I get no insert.
Here is where I am calling the insert class that uses JSON and implements AsyncTask:
package us.jtaylorok.android.sqlite.first;
import java.util.ArrayList;
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 android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
public class RemoteInsert extends AsyncTask<Void, String,String >{
protected String TAG;
protected Context context;
protected String input;
protected ProgressDialog progressDialog;
public RemoteInsert(String i,Context c){
this.input = i;
this.context = c;
}
protected void onPreExecute() {
//ProgressDialog progressDialog; // = new ProgressDialog(context);
//progressDialog=ProgressDialog.show(,"Please Wait..","Sending data to database", false);
progressDialog=ProgressDialog.show(context,"Please Wait..","Sending data to database", false);
}
#Override
protected String doInBackground(Void... params) {
try {
HttpClient httpclient = new DefaultHttpClient();
//HttpPost httppost = new HttpPost("http://localhost/index.php");
//HttpPost httppost = new HttpPost("http://10.253.8.88/patient_data/patient_data.php");
HttpPost httppost = new HttpPost("http://10.100.205.72/patient_data/patient_data.php");
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("entry", "Input from Android"));
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
HttpResponse response = httpclient.execute(httppost);
Log.i("postData", response.getStatusLine().toString());
} catch(Exception e) {
Log.e(TAG, "Error: "+e.toString());
}
return "";
}
protected void onPostExecute(String result) {
progressDialog.dismiss();
Toast.makeText(context, "Finished", Toast.LENGTH_LONG).show();
}
}
And here is my PHP script:
<?php
// mysql_connect("host","username","password");
mysql_connect("localhost","user1","mypassword");
mysql_select_db("test");
$entry_value = $_REQUEST["entry"];
$query = "INSERT INTO patientdata (entry) values (".$entry_value.");";
if( !mysql_query($query) ) {
/*insert failed*/
}
mysql_close();
?>
Again, this works perfectly if I call it from the browser, but it throws an exception before implementing AsyncTask.
I do get the AVD to display the add and remove, but when I do that there is no request in my apache2 access_log or error_log. Any suggestions?
I think you have stored php script on local server. So use this 10.0.2.2 while initializing HttpPost instead of your machine's ip address. Its localhost equivalent in android Virtual device.
That was not the issue for this particular problem. The issue was a magic quotes setting in the php.ini