Send a string to a servlet from android - java

I am trying to send a string from a android application to a servlet and then retrieve that string to my android application ,but when i try to invoke the servlet it force close on me
and i dont know why (im very new to android and this is a practice exercise for me)
here is my android simple app:
ANDROID
package com.theopentutorials.android;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class HttpGetServletActivity extends Activity implements OnClickListener {
Button button;
TextView outputText;
public static String request = "kjo ishte e gjitha";
public static final String URL = ("http://10.0.2.2:8080/HttpGetServlet/HelloWorldServlet?param1=" + request);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewsById();
button.setOnClickListener(this);
}
private void findViewsById() {
button = (Button) findViewById(R.id.button);
outputText = (TextView) findViewById(R.id.outputTxt);
}
public void onClick(View view) {
GetXMLTask task = new GetXMLTask();
task.execute(new String[] { URL });
}
private class GetXMLTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String output = null;
for (String url : urls) {
output = getOutputFromUrl(url);
}
return output;
}
private String getOutputFromUrl(String url) {
StringBuffer output = new StringBuffer("");
try {
InputStream stream = getHttpConnection(url);
BufferedReader buffer = new BufferedReader(
new InputStreamReader(stream));
String s = "";
while ((s = buffer.readLine()) != null)
output.append(s);
} catch (IOException e1) {
e1.printStackTrace();
}
return output.toString();
}
private InputStream getHttpConnection(String urlString)
throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}
#Override
protected void onPostExecute(String output) {
outputText.setText(output);
}
}
}
and here is my simple servlet
SERVLET
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/HelloWorldServlet")
public class HelloWorldServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public HelloWorldServlet() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String par1 = request.getParameter("param1");
PrintWriter out = response.getWriter();
out.println(par1);
}
}
And the logcat log error says
01-10 13:36:50.014: E/AndroidRuntime(1187): FATAL EXCEPTION: AsyncTask #1
01-10 13:36:50.014: E/AndroidRuntime(1187): java.lang.RuntimeException: An error occured while executing doInBackground()
01-10 13:36:50.014: E/AndroidRuntime(1187): at android.os.AsyncTask$3.done(AsyncTask.java:299)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
01-10 13:36:50.014: E/AndroidRuntime(1187): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.lang.Thread.run(Thread.java:856)
01-10 13:36:50.014: E/AndroidRuntime(1187): Caused by: java.lang.NullPointerException: lock == null
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.io.Reader.<init>(Reader.java:64)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.io.InputStreamReader.<init>(InputStreamReader.java:122)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.io.InputStreamReader.<init>(InputStreamReader.java:59)
01-10 13:36:50.014: E/AndroidRuntime(1187): at com.theopentutorials.android.HttpGetServletActivity$GetXMLTask.getOutputFromUrl(HttpGetServletActivity.java:64)
01-10 13:36:50.014: E/AndroidRuntime(1187): at com.theopentutorials.android.HttpGetServletActivity$GetXMLTask.doInBackground(HttpGetServletActivity.java:54)
01-10 13:36:50.014: E/AndroidRuntime(1187): at com.theopentutorials.android.HttpGetServletActivity$GetXMLTask.doInBackground(HttpGetServletActivity.java:1)
01-10 13:36:50.014: E/AndroidRuntime(1187): at android.os.AsyncTask$2.call(AsyncTask.java:287)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
01-10 13:36:50.014: E/AndroidRuntime(1187): ... 4 more
doest somebody have any idea ?
Thank you for your help in advance !
Have a nice day!

You need to add the internet access permission
<uses-permission android:name="android.permission.INTERNET"/>
I found that you should use the URLEncoder to encode the url because your url contains spaces. Please check http://developer.android.com/reference/java/net/URLEncoder.html

You have forgot to set param1 from your android app.
connection.setRequestProperty("param1", "Your String Value");
then you will get the value back as response from Servlet.

Related

error consuming online webservice from android

I have created webservice which is working on local machine, and i have successfully consume it in android app without any error. But when i am hosting my webservice at online server, i am getting a fatal error exception. Below is my android code and error log.
error log:-
03-12 10:57:54.935: W/dalvikvm(7491): threadid=15: thread exiting with uncaught exception (group=0x420d8898)
03-12 10:57:54.935: E/AndroidRuntime(7491): FATAL EXCEPTION: AsyncTask #4
03-12 10:57:54.935: E/AndroidRuntime(7491): java.lang.RuntimeException: An error occured while executing doInBackground()
03-12 10:57:54.935: E/AndroidRuntime(7491): at android.os.AsyncTask$3.done(AsyncTask.java:299)
03-12 10:57:54.935: E/AndroidRuntime(7491): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
03-12 10:57:54.935: E/AndroidRuntime(7491): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
03-12 10:57:54.935: E/AndroidRuntime(7491): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
03-12 10:57:54.935: E/AndroidRuntime(7491): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
03-12 10:57:54.935: E/AndroidRuntime(7491): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
03-12 10:57:54.935: E/AndroidRuntime(7491): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
03-12 10:57:54.935: E/AndroidRuntime(7491): at java.lang.Thread.run(Thread.java:841)
03-12 10:57:54.935: E/AndroidRuntime(7491): Caused by: java.lang.NullPointerException
03-12 10:57:54.935: E/AndroidRuntime(7491): at com.example.test.MainActivity$MyAsyncTask1.doInBackground(MainActivity.java:106)
03-12 10:57:54.935: E/AndroidRuntime(7491): at com.example.test.MainActivity$MyAsyncTask1.doInBackground(MainActivity.java:1)
03-12 10:57:54.935: E/AndroidRuntime(7491): at android.os.AsyncTask$2.call(AsyncTask.java:287)
03-12 10:57:54.935: E/AndroidRuntime(7491): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
03-12 10:57:54.935: E/AndroidRuntime(7491): ... 4 more
03-12 10:57:54.965: I/Process(7491): Sending signal. PID: 7491 SIG: 9
my andorid code:-
package com.example.test;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.support.v7.app.ActionBarActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
EditText name;
TextView email;
Button Btnfetch;
String[] arr;
private Handler mHandler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try
{
name = (EditText)findViewById(R.id.name);
email = (TextView)findViewById(R.id.email);
Btnfetch = (Button)findViewById(R.id.button1);
Btnfetch.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
String sname = name.getText().toString();
String[] params = new String[]{"my_ip_address of webservice/",sname};
new MyAsyncTask1().execute(params);
}
});
}
catch(Exception ex)
{
//Message(ex);
Toast.makeText(this, "null", Toast.LENGTH_LONG).show();
}
}
class MyAsyncTask1 extends AsyncTask<String, Void, String>
{
public String SOAP_ACTION = "http://tempuri.org/Getemail";
public String OPERATION_NAME = "Getemail";
public String WSDL_TARGET_NAMESPACE = "http://tempuri.org/";
public String SOAP_ADDRESS;
private SoapObject request;
private HttpTransportSE httpTransport;
Object response = null;
//this method will fetch output from webservice
#Override
protected String doInBackground(String... params)
{
SOAP_ADDRESS = "http://"+params[0]+"PCGws.asmx";
request = new SoapObject(WSDL_TARGET_NAMESPACE, OPERATION_NAME);
PropertyInfo pi = new PropertyInfo();
pi.setName("Name");
pi.setValue(params[1]);
pi.setType(String.class);
request.addProperty(pi);
pi = new PropertyInfo();
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
httpTransport = new HttpTransportSE(SOAP_ADDRESS);
try
{
httpTransport.call(SOAP_ACTION, envelope);
response = envelope.getResponse();
Log.d("result", response.toString());
}
catch(Exception exp)
{
response = exp.getMessage();
}
return response.toString();
}
protected void onPostExecute(final String result)
{
//result parameter should be final so that it can be use in cross thread operation
super.onPostExecute(result);
//we have to use async handler to make changes in view text
mHandler.post(new Runnable()
{
#Override
public void run()
{
arr=result.split(",");
email.setText(arr[0]);
}
});
}
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

Android Asynctask with PHP not working

I have been stuck for weeks.....for this problem
I am using AsynTask to send data to php and recieve a name to print
but it showed this error anyone to help ??
12-29 19:34:12.623: D/dalvikvm(799): GC_CONCURRENT freed 188K, 11% free 2629K/2948K, paused 25ms+61ms, total 218ms
12-29 19:34:13.282: D/gralloc_goldfish(799): Emulator without GPU emulation detected.
12-29 19:34:42.132: W/System.err(799): java.lang.NullPointerException
12-29 19:34:42.164: W/System.err(799): at android.app.Activity.findViewById(Activity.java:1839)
12-29 19:34:42.164: W/System.err(799): at com.example.myweb.MainActivity.afterEffect(MainActivity.java:64)
12-29 19:34:42.164: W/System.err(799): at com.example.myweb.toPHP.onPreExecute(toPHP.java:47)
12-29 19:34:42.164: W/System.err(799): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
12-29 19:34:42.164: W/System.err(799): at android.os.AsyncTask.execute(AsyncTask.java:534)
12-29 19:34:42.164: W/System.err(799): at com.example.myweb.MainActivity$1.onClick(MainActivity.java:54)
12-29 19:34:42.172: W/System.err(799): at android.view.View.performClick(View.java:4204)
12-29 19:34:42.172: W/System.err(799): at android.view.View$PerformClick.run(View.java:17355)
12-29 19:34:42.172: W/System.err(799): at android.os.Handler.handleCallback(Handler.java:725)
12-29 19:34:42.185: W/System.err(799): at android.os.Handler.dispatchMessage(Handler.java:92)
12-29 19:34:42.185: W/System.err(799): at android.os.Looper.loop(Looper.java:137)
12-29 19:34:42.192: W/System.err(799): at android.app.ActivityThread.main(ActivityThread.java:5041)
12-29 19:34:42.212: W/System.err(799): at java.lang.reflect.Method.invokeNative(Native Method)
12-29 19:34:42.212: W/System.err(799): at java.lang.reflect.Method.invoke(Method.java:511)
12-29 19:34:42.212: W/System.err(799): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
12-29 19:34:42.222: W/System.err(799): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
12-29 19:34:42.222: W/System.err(799): at dalvik.system.NativeStart.main(Native Method)
JSONParser.java
package com.example.myweb;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, List params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
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();
json = sb.toString();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
toPHP.java
package com.example.myweb;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
public class toPHP extends AsyncTask {
MainActivity main = new MainActivity();
private JSONParser jsonParser;
String email,password;
EditText emailBox;
EditText passwordBox;
#Override
protected void onPreExecute() {
super.onPreExecute();
main.afterEffect("sending...");
emailBox = (EditText) main.findViewById(R.id.email);
passwordBox = (EditText) main.findViewById(R.id.password);
email = emailBox.getText().toString();
password = passwordBox.getText().toString();
}
protected JSONObject doInBackground(String... args) {
toPHP userFunction = new toPHP();
JSONObject json = null;
try {
json = userFunction.getUserLoggedIn(email, password);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return json;
}
public JSONObject getUserLoggedIn(String email,String password) throws ClientProtocolException, IOException, JSONException{
JSONObject json = null;
/*
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://localhost/testand.php");
*/
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("email", email));
pairs.add(new BasicNameValuePair("password", password));
//post.setEntity(new UrlEncodedFormEntity(pairs));
//HttpResponse response = client.execute(post);
//HttpEntity resEntity = response.getEntity();
//if (resEntity != null) {
//String responseStr = EntityUtils.toString(resEntity).trim();
json = jsonParser.getJSONFromUrl("http://localhost/testand.php", pairs);
//}
return json;
}
protected void onPostExecute(JSONObject json) throws JSONException {
String myName = json.getString("name");
String str = myName + ", Welcome to Socionet. :) ";
main.afterEffect(str);
}
#Override
protected Object doInBackground(Object... params) {
// TODO Auto-generated method stub
return null;
}
}
MainActivity.java
package com.example.myweb;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
public class MainActivity extends Activity {
Button button;
EditText emailBox;
EditText passwordBox;
String emailId;
String passwordId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.login1);
emailBox = (EditText)findViewById(R.id.email);
passwordBox = (EditText)findViewById(R.id.password);
button.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
try {
new toPHP().execute();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public void afterEffect(String str){
TextView textV1 = (TextView)findViewById(R.id.textV1);
textV1.setText(str);
}
}
UPDATE 1
new errors after #hasan83 's fixes
12-29 21:38:27.588: W/dalvikvm(1283): threadid=11: thread exiting with uncaught exception (group=0x40a71930)
12-29 21:38:27.748: E/AndroidRuntime(1283): FATAL EXCEPTION: AsyncTask #1
12-29 21:38:27.748: E/AndroidRuntime(1283): java.lang.RuntimeException: An error occured while executing doInBackground()
12-29 21:38:27.748: E/AndroidRuntime(1283): at android.os.AsyncTask$3.done(AsyncTask.java:299)
12-29 21:38:27.748: E/AndroidRuntime(1283): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
12-29 21:38:27.748: E/AndroidRuntime(1283): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
12-29 21:38:27.748: E/AndroidRuntime(1283): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
12-29 21:38:27.748: E/AndroidRuntime(1283): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
12-29 21:38:27.748: E/AndroidRuntime(1283): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
12-29 21:38:27.748: E/AndroidRuntime(1283): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
12-29 21:38:27.748: E/AndroidRuntime(1283): at java.lang.Thread.run(Thread.java:856)
12-29 21:38:27.748: E/AndroidRuntime(1283): Caused by: java.lang.NullPointerException
12-29 21:38:27.748: E/AndroidRuntime(1283): at com.example.myweb.toPHP.getUserLoggedIn(toPHP.java:99)
12-29 21:38:27.748: E/AndroidRuntime(1283): at com.example.myweb.toPHP.doInBackground(toPHP.java:67)
12-29 21:38:27.748: E/AndroidRuntime(1283): at com.example.myweb.toPHP.doInBackground(toPHP.java:1)
12-29 21:38:27.748: E/AndroidRuntime(1283): at android.os.AsyncTask$2.call(AsyncTask.java:287)
12-29 21:38:27.748: E/AndroidRuntime(1283): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
12-29 21:38:27.748: E/AndroidRuntime(1283): ... 4 more
You can't create a new MainActivity in your AsyncTask. When you are in your MainActivity, pass the activity to the constructor of the AsyncTask. You will be able to get and update your views in the onPreExecute() method.
public class toPHP extends AsyncTask {
public toPHP(Activity activity) {
}
}
And in your activity:
new toPHP(MainActivity.this).execute();
Add a constructor so that you can pass in the current MainActivity to your AsyncTask
public class toPHP extends AsyncTask {
final MainActivity main;
public toPHP(MainActivity main) {
this.main = main;
}
...
then call like so
button.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
try {
new toPHP(MainActivity.this).execute();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
Error says it's unable to find your TextView with id of R.id.textV1. Make sure it's available in the content view :R.layout.activity_main
But the main problem is why are you doing this MainActivity main = new MainActivity(), in your AsyncTask. It should be passed by reference from the actual Activity.
Points:
I don't see #Override keyword before onPostExecute and doInBackground methods.
Move the code in onPreExecute to doInBackground.
Send the main activity as a parameter for the AsynkTask execute method.
Catch the activity on the do doInBackground.
dont' declare an object of toPhp just call getUserLoggedIn. you are in the same class.
That's it.
new toPHP().execute(MainActivity.this);
#Override
protected Object doInBackground(Object... args) {
main = (MainActivity) args[0];
main.afterEffect("sending...");
emailBox = (EditText) main.findViewById(R.id.email);
passwordBox = (EditText) main.findViewById(R.id.password);
email = emailBox.getText().toString();
password = passwordBox.getText().toString();
..
}

Android VerifyError crash using jackson parser

Here is my log cat. Unfortunately I am not a pro in reading errors from logcat so please help me :)
05-30 12:12:16.510: I/System.out(838): We made it this far 1
05-30 12:12:17.230: I/System.out(838): We made it this far 2
05-30 12:12:17.240: W/dalvikvm(838): VFY: unable to resolve exception class 748 (Lcom/fasterxml/jackson/core/JsonParseException;)
05-30 12:12:17.240: W/dalvikvm(838): VFY: unable to find exception handler at addr 0x2a
05-30 12:12:17.240: W/dalvikvm(838): VFY: rejected Lcom/example/bitmapdisplay/MainActivity$URLArray;.doInBackground ([Ljava/lang/Void;)Ljava/lang/Void;
05-30 12:12:17.240: W/dalvikvm(838): VFY: rejecting opcode 0x0d at 0x002a
05-30 12:12:17.250: W/dalvikvm(838): VFY: rejected Lcom/example/bitmapdisplay/MainActivity$URLArray;.doInBackground ([Ljava/lang/Void;)Ljava/lang/Void;
05-30 12:12:17.250: W/dalvikvm(838): Verifier rejected class Lcom/example/bitmapdisplay/MainActivity$URLArray;
05-30 12:12:17.250: D/AndroidRuntime(838): Shutting down VM
05-30 12:12:17.250: W/dalvikvm(838): threadid=1: thread exiting with uncaught exception (group=0xb1adaba8)
05-30 12:12:17.270: E/AndroidRuntime(838): FATAL EXCEPTION: main
05-30 12:12:17.270: E/AndroidRuntime(838): Process: com.example.bitmapdisplay, PID: 838
05-30 12:12:17.270: E/AndroidRuntime(838): java.lang.VerifyError: com/example/bitmapdisplay/MainActivity$URLArray
05-30 12:12:17.270: E/AndroidRuntime(838): at com.example.bitmapdisplay.MainActivity.onCreate(MainActivity.java:72)
05-30 12:12:17.270: E/AndroidRuntime(838): at android.app.Activity.performCreate(Activity.java:5231)
05-30 12:12:17.270: E/AndroidRuntime(838): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
05-30 12:12:17.270: E/AndroidRuntime(838): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
05-30 12:12:17.270: E/AndroidRuntime(838): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
05-30 12:12:17.270: E/AndroidRuntime(838): at android.app.ActivityThread.access$800(ActivityThread.java:135)
05-30 12:12:17.270: E/AndroidRuntime(838): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
05-30 12:12:17.270: E/AndroidRuntime(838): at android.os.Handler.dispatchMessage(Handler.java:102)
05-30 12:12:17.270: E/AndroidRuntime(838): at android.os.Looper.loop(Looper.java:136)
05-30 12:12:17.270: E/AndroidRuntime(838): at android.app.ActivityThread.main(ActivityThread.java:5017)
05-30 12:12:17.270: E/AndroidRuntime(838): at java.lang.reflect.Method.invokeNative(Native Method)
05-30 12:12:17.270: E/AndroidRuntime(838): at java.lang.reflect.Method.invoke(Method.java:515)
05-30 12:12:17.270: E/AndroidRuntime(838): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
05-30 12:12:17.270: E/AndroidRuntime(838): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
05-30 12:12:17.270: E/AndroidRuntime(838): at dalvik.system.NativeStart.main(Native Method)
05-30 12:12:30.390: I/Process(838): Sending signal. PID: 838 SIG: 9
Here is the logcat code and here is my Java code. It seems like the problems are coming from the thread URLArray because, as seen in the logcat, the system doesn't even print the third "we made it this far":
package com.example.bitmapdisplay;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import com.fasterxml.jackson.core.JsonParseException;
import android.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
public class MainActivity extends Activity {
/**
* Bitmap items na dimage displaying
*/
Bitmap image;
BitmapDrawable bd;
ImageView temp;
ProgressDialog pd;
/**
* JSON URL
*/
URL url;
/**
* Data from JSON file
*/
ArrayList<String> urls;
ArrayList<ImageView> images;
JsonParsing obj;
String json_link_str = "http://api.tumblr.com/v2/blog/humansofnewyork.com/posts?api_key=7ag2CJXOuxuW3vlVS5wQG6pYA6a2ZQcSCjzZsAp2pDbVwf3xEk&notes_info=true&filter=text";
int counter;
#Override
protected void onCreate(Bundle savedInstanceState) {
System.out.println(" We made it this far 1");
super.onCreate(savedInstanceState);
setContentView(com.example.bitmapdisplay.R.layout.image_container);
counter = 0;
images = new ArrayList<ImageView>();
urls = new ArrayList<String>();
System.out.println(" We made it this far 2");
new URLArray().execute();
}
/**
* Fills the ListView
*/
private void fillGridView() {
ArrayAdapter<ImageView> adapter = new ArrayAdapter<ImageView>(this, com.example.bitmapdisplay.R.layout.image_container,images);
GridView grid = (GridView) findViewById(com.example.bitmapdisplay.R.id.gvImages);
grid.setAdapter(adapter);
}
public class URLArray extends AsyncTask<Void, Void, Void > {
public URLArray() {
}
#Override
protected Void doInBackground(Void...params ) {
try {
System.out.println(" We made it this far 3");
URL json_link = new URL(json_link_str);
JsonParsing parse_images = new JsonParsing(json_link);
try {
parse_images.parseFile(3, urls);
System.out.println(" We made it this far 4");
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
obj = parse_images;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void arg) {
super.onPreExecute();
System.out.println(" We made it this far 5");
urls = obj.getURLs();
new TheTask().execute();
}
}
class TheTask extends AsyncTask<Void,Void,Void>
{
#Override
protected Void doInBackground(Void... params) {
System.out.println(" We made it this far 6");
pd = new ProgressDialog(MainActivity .this);
pd.show();
System.out.println(" We made it this far 7");
try
{
int counter = 0;
for (ImageView temp : images) {
image = downloadBitmap(urls.get(counter));
temp.setImageBitmap(image);
images.add(temp);
counter++;
}
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
System.out.println(" We made it this far 8");
super.onPostExecute(result);
pd.dismiss();
if(image!=null)
{
fillGridView();
}
}
}
private Bitmap downloadBitmap(String url) {
// initilize the default HTTP client object
final DefaultHttpClient client = new DefaultHttpClient();
//forming a HttoGet request
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
//check 200 OK for success
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w("ImageDownloader", "Error " + statusCode +
" while retrieving bitmap from " + url);
return null;
}
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
// getting contents from the stream
inputStream = entity.getContent();
// decoding stream data back into image Bitmap that android understands
image = BitmapFactory.decodeStream(inputStream);
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (Exception e) {
// You Could provide a more explicit error message for IOException
getRequest.abort();
Log.e("ImageDownloader", "Something went wrong while" +
" retrieving bitmap from " + url + e.toString());
}
return image;
}
}
The key problem is here
05-30 12:12:17.240: W/dalvikvm(838): VFY: unable to resolve exception class 748 (Lcom/fasterxml/jackson/core/JsonParseException;)
05-30 12:12:17.240: W/dalvikvm(838): VFY: unable to find exception handler at addr 0x2a
05-30 12:12:17.240: W/dalvikvm(838): VFY: rejected Lcom/example/bitmapdisplay/MainActivity$URLArray;.doInBackground ([Ljava/lang/Void;)Ljava/lang/Void;
05-30 12:12:17.240: W/dalvikvm(838): VFY: rejecting opcode 0x0d at 0x002a
05-30 12:12:17.250: W/dalvikvm(838): VFY: rejected Lcom/example/bitmapdisplay/MainActivity$URLArray;.doInBackground ([Ljava/lang/Void;)Ljava/lang/Void;
05-30 12:12:17.250: W/dalvikvm(838): Verifier rejected class Lcom/example/bitmapdisplay/MainActivity$URLArray;
and it all goes downhill from there.
Looks like JsonParseException (and possibly other classes from Jackson) are not being included in your APK. This could happen if they're not being exported by Eclipse.
Instead of adding it as an external library, just place jackson-core-x.x.x.jar in the libs folder of your Android project and it should be enough to ensure this.

Pass edittext value from android to web services

I want to pass edit text value from android to web services, but i can not do that every time it returns a null value.
This is my simple web services.
package org.me.mongodb;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.ejb.Stateless;
#WebService(serviceName = "Simple")
#Stateless()
public class Simple {
public String testMyProps(#WebParam(name = "name")String fname){
return "First Name : "+fname;
}
}
and android code;
package com.prgguru.android;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import com.example.webserviceactivity.R;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private static final String SOAP_ACTION = "";
private static final String METHOD_NAME = "testMyProps";
private static final String NAMESPACE = "http://mongodb.me.org/";
private static final String URL = "http://10.0.2.2:8080/Simple/Simple?WSDL";
private String TAG = "PGGURU";
private static String barge="";
private static String info;
Button b;
TextView tv;
EditText et;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
et = (EditText) findViewById(R.id.editText1);
tv = (TextView) findViewById(R.id.tv_result);
//Button to trigger web service invocation
b = (Button) findViewById(R.id.button1);
//Button Click Listener
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Check if barge text control is not empty
if (et.getText().length() != 0 && et.getText().toString() != "") {
//Get the text control value
barge = et.getText().toString();
//Create instance for AsyncCallWS
AsyncCallWS task = new AsyncCallWS();
//Call execute
task.execute();
//If text control is empty
} else {
tv.setText("Please enter Barge Name");
}
}
});
}
public void testMyProps(String fname) {
//Create request
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
//Property which holds input parameters
PropertyInfo getinfo = new PropertyInfo();
//Set Name
getinfo.setName("arg0");
//Set Value
getinfo.setValue(fname);
//Set dataType
getinfo.setType(String.class);
//Add the property to request object
request.addProperty(getinfo);
//Create envelope
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
//Set output SOAP object
envelope.setOutputSoapObject(request);
//Create HTTP call object
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
//Invole web service
androidHttpTransport.call(SOAP_ACTION, envelope);
//Get the response
SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
//Assign it to info static variable
info = response.toString();
} catch (Exception e) {
e.printStackTrace();
}
}
private class AsyncCallWS extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
Log.i(TAG, "doInBackground");
testMyProps(barge);
return null;
}
#Override
protected void onPostExecute(Void result) {
Log.i(TAG, "onPostExecute");
tv.setText(info);
}
#Override
protected void onPreExecute() {
Log.i(TAG, "onPreExecute");
tv.setText("Getting...");
}
#Override
protected void onProgressUpdate(Void... values) {
Log.i(TAG, "onProgressUpdate");
}
}
}
It returns First name null;
Please help i think i cannot pass the value to web services.
Thanks a lot.
Iam getting this error,
12-11 09:45:53.291: E/AndroidRuntime(1920): FATAL EXCEPTION: main
12-11 09:45:53.291: E/AndroidRuntime(1920): java.lang.IllegalStateException: Cannot execute task: the task is already running.
12-11 09:45:53.291: E/AndroidRuntime(1920): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:575)
12-11 09:45:53.291: E/AndroidRuntime(1920): at android.os.AsyncTask.execute(AsyncTask.java:534)
12-11 09:45:53.291: E/AndroidRuntime(1920): at com.prgguru.android.MainActivity$1.onClick(MainActivity.java:57)
12-11 09:45:53.291: E/AndroidRuntime(1920): at android.view.View.performClick(View.java:4240)
12-11 09:45:53.291: E/AndroidRuntime(1920): at android.view.View$PerformClick.run(View.java:17721)
12-11 09:45:53.291: E/AndroidRuntime(1920): at android.os.Handler.handleCallback(Handler.java:730)
12-11 09:45:53.291: E/AndroidRuntime(1920): at android.os.Handler.dispatchMessage(Handler.java:92)
12-11 09:45:53.291: E/AndroidRuntime(1920): at android.os.Looper.loop(Looper.java:137)
12-11 09:45:53.291: E/AndroidRuntime(1920): at android.app.ActivityThread.main(ActivityThread.java:5103)
12-11 09:45:53.291: E/AndroidRuntime(1920): at java.lang.reflect.Method.invokeNative(Native Method)
12-11 09:45:53.291: E/AndroidRuntime(1920): at java.lang.reflect.Method.invoke(Method.java:525)
12-11 09:45:53.291: E/AndroidRuntime(1920): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
12-11 09:45:53.291: E/AndroidRuntime(1920): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-11 09:45:53.291: E/AndroidRuntime(1920): at dalvik.system.NativeStart.main(Native Method)
12-11 09:45:55.031: I/Process(1920): Sending signal. PID: 1920 SIG: 9
You are setting barge with the EditText value but you are not sending it inside AsyncTask
barge = et.getText().toString();
//Create instance for AsyncCallWS
AsyncCallWS task = new AsyncCallWS();
if(barge != null && !barge.equals("")) { // if barge is not an empty string and not null
task.execute(barge);
// return null; i don't think u need this return statement
}
And then in your AsyncTask Class
#Override
protected Void doInBackground(String... params) {
Log.i(TAG, "doInBackground: barge is " + params[0]);
testMyProps(params[0]);
}
I think when you instantiate AsyncCallWS, you will have to send the barge in as params.

Unfortunately app has stopped working [duplicate]

This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 9 years ago.
I am new to android application development. I was doing this tutorial app.
When I run it in the emulator ,it says "Unfortunately AndroidJSONParsingActivity has stopped working.
" There are no errors in the code. The API level is 17 and the emulator is Nexus S.
Please help me out.
I got the tutorial CODE from JSON tutorial
AndroidJsonParsing.java
package com.example.androidjsonparsingactivity;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class AndroidJSONParsing extends ListActivity {
// url to make request
private static String url = "http://api.androidhive.info/contacts/";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray contacts = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = json.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone number is agin JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_EMAIL, email);
map.put(TAG_PHONE_MOBILE, mobile);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.list_item,
new String[] { TAG_NAME, TAG_EMAIL, TAG_PHONE_MOBILE }, new int[] {
R.id.name, R.id.email, R.id.mobile });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.email)).getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_PHONE_MOBILE, description);
startActivity(in);
}
});
}
}
JSONParser.java
package com.example.androidjsonparsingactivity;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
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();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
SingleMenuItemActivity.java
package com.example.androidjsonparsingactivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class SingleMenuItemActivity extends Activity {
// JSON node keys
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_PHONE_MOBILE = "mobile";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_list_item);
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
String name = in.getStringExtra(TAG_NAME);
String cost = in.getStringExtra(TAG_EMAIL);
String description = in.getStringExtra(TAG_PHONE_MOBILE);
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblCost = (TextView) findViewById(R.id.email_label);
TextView lblDesc = (TextView) findViewById(R.id.mobile_label);
lblName.setText(name);
lblCost.setText(cost);
lblDesc.setText(description);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.androidjsonparsingactivity"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.androidjsonparsingactivity.AndroidJSONParsing"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SingleListItem"
android:label="Single Item Selected"></activity>
</application>
</manifest>
Logcat
08-01 07:32:35.531: D/dalvikvm(1121): GC_FOR_ALLOC freed 42K, 7% free 2609K/2792K, paused 37ms, total 41ms
08-01 07:32:35.541: I/dalvikvm-heap(1121): Grow heap (frag case) to 3.288MB for 635812-byte allocation
08-01 07:32:35.591: D/dalvikvm(1121): GC_FOR_ALLOC freed 2K, 6% free 3227K/3416K, paused 47ms, total 47ms
08-01 07:32:35.672: D/dalvikvm(1121): GC_CONCURRENT freed <1K, 6% free 3237K/3416K, paused 9ms+16ms, total 82ms
08-01 07:32:35.740: D/AndroidRuntime(1121): Shutting down VM
08-01 07:32:35.740: W/dalvikvm(1121): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
08-01 07:32:35.761: E/AndroidRuntime(1121): FATAL EXCEPTION: main
08-01 07:32:35.761: E/AndroidRuntime(1121): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.androidjsonparsingactivity/com.example.androidjsonparsingactivity.AndroidJSONParsing}: android.os.NetworkOnMainThreadException
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.app.ActivityThread.access$600(ActivityThread.java:141)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.os.Handler.dispatchMessage(Handler.java:99)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.os.Looper.loop(Looper.java:137)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.app.ActivityThread.main(ActivityThread.java:5041)
08-01 07:32:35.761: E/AndroidRuntime(1121): at java.lang.reflect.Method.invokeNative(Native Method)
08-01 07:32:35.761: E/AndroidRuntime(1121): at java.lang.reflect.Method.invoke(Method.java:511)
08-01 07:32:35.761: E/AndroidRuntime(1121): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
08-01 07:32:35.761: E/AndroidRuntime(1121): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
08-01 07:32:35.761: E/AndroidRuntime(1121): at dalvik.system.NativeStart.main(Native Method)
08-01 07:32:35.761: E/AndroidRuntime(1121): Caused by: android.os.NetworkOnMainThreadException
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
08-01 07:32:35.761: E/AndroidRuntime(1121): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
08-01 07:32:35.761: E/AndroidRuntime(1121): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
08-01 07:32:35.761: E/AndroidRuntime(1121): at java.net.InetAddress.getAllByName(InetAddress.java:214)
08-01 07:32:35.761: E/AndroidRuntime(1121): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
08-01 07:32:35.761: E/AndroidRuntime(1121): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
08-01 07:32:35.761: E/AndroidRuntime(1121): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
08-01 07:32:35.761: E/AndroidRuntime(1121): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
08-01 07:32:35.761: E/AndroidRuntime(1121): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
08-01 07:32:35.761: E/AndroidRuntime(1121): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
08-01 07:32:35.761: E/AndroidRuntime(1121): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
08-01 07:32:35.761: E/AndroidRuntime(1121): at com.example.androidjsonparsingactivity.JSONParser.getJSONFromUrl(JSONParser.java:38)
08-01 07:32:35.761: E/AndroidRuntime(1121): at com.example.androidjsonparsingactivity.AndroidJSONParsing.onCreate(AndroidJSONParsing.java:54)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.app.Activity.performCreate(Activity.java:5104)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
08-01 07:32:35.761: E/AndroidRuntime(1121): ... 11 more
For Android 4.0 and above you cant do network operations on UI Thread and need to use background threads.
You are calling the following code from the main thread instead of
background thread therefore this exception is thrown .
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
Instead create a async task and perform this in the doInBackground() of the async task
Async task performs the opertaion in background instead of performing it on the main /UI thread
class FetchJsonTask extends AsyncTask<Void, Void, void> {
protected Void doInBackground(Void... params) {
try {
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
} catch (Exception e) {
}
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//code to be executed after background task is finished
}
protected void onPreExecute() {
super.onPreExecute();
//code to be executed before background task is started
}
return null;
}
In onCreate() call the execute the async task in the following way :
new FetchJsonTask().execute();
Related Link:
How to fix android.os.NetworkOnMainThreadException?
you have called the Web from main thread. that's why you have got
Caused by: android.os.NetworkOnMainThreadException
after android 4.0 you cant do network operations on its UIThread. you need to use background threads. i will prefer to use AsyncTask for network call.
Hope it Helps!!
read commented parts and change your code according to that.
class MyAsync extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(String... params) {
// do your JSON parse here
return null;
}
#Override
protected void onPostExecute(Void result) {
// after gettin json data do whatever you want here
super.onPostExecute(result);
}
}
call your async class in your oncreate as:
new MyAsync().execute();

Categories

Resources