HTTP request that throws a null exception - android

I have an activity that create a new instance of connection. like this:
public class myActivity extends Activity {
TextView tv;
ProgressDialog dialog = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.daily_news);
gestureDetector = new GestureDetector(new SwipeGestureDetector());
tv = (TextView) findViewById(R.id.tx);
dialog = ProgressDialog.show(myActivity.this, "","Validating user...", true);
connection con = new connection(dialog);
final String str =con.connect_to_db("http://10.0.2.2:8000/daily/my.php");
runOnUiThread(new Runnable() {
public void run() {
tv.setText(str);
dialog.dismiss();
}
});
}
}
in connection class i have an HttpResponse that returns null. like this:
public class connection {
private HttpPost httppost;
private HttpClient httpclient;
private HttpResponse response;
private ProgressDialog dialog = null;
private String result;
public connection(ProgressDialog di){
dialog = di;
}
public String connect_to_db(String url){
try{
httpclient=new DefaultHttpClient();
httppost= new HttpPost(url);
response=httpclient.execute(httppost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
result = httpclient.execute(httppost, responseHandler);
}catch(Exception e){
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
return result;
}
}
why the value of "result" in connection class is null?

This line:
final String str =con.connect_to_db("http://10.0.2.2:8000/daily/my.php");
Should not be written in the onCreate, but rather in a separate thread => NetworkOnMainThreadException
For your NullPointer, please tell us if you have the Internet permission in Manifest and if response is null or not.

May be because you are doing network operation in onCreate Method. It will not create any problem if you are using android2.2, but if it is HoneyComb then chances are that it is causing some exception and finally you are getting null value. Move the code to onResume() method.
For Simplicity use
HttpResponse response = httpclient.execute(httppost);
and
String valueString = EntityUtils.toString(response.getEntity());
int statusCode = response.getStatusLine().getStatusCode();
print these values and see the out put.

Related

NetworkOnMainThreadException

Trying to read and parse some json data in my app. I implemented Parser class extending AsyncTask as follows:
public class JSONParser extends AsyncTask<Void, Void, String> {
private String strUrl;
private List<NameValuePair> params;
private String result;
private String response;
public static final String RESULT_SUCCESS = "success";
public static final String RESULT_FAILED = "failed";
public JSONParser(String strUrl, List<NameValuePair> params) {
this.strUrl = strUrl;
this.params = params;
}
private void parse() {
try {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(strUrl);
// Add parameters
if (params != null) {
httppost.setEntity(new UrlEncodedFormEntity(params));
}
// Execute HTTP Post Request
HttpResponse httpResponse = httpclient.execute(httppost);
// return by response
result = RESULT_SUCCESS;
this.response = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
} catch (Exception e) {
result = RESULT_FAILED;
this.response = null;
e.printStackTrace();
}
}
#Override
public String doInBackground(Void... params) {
parse();
return response;
}
public String getResult() {
return result;
}
public String getResponse() {
return response;
}
}
It works well in later android versions, but unfortunately it throws NetworkOnMainThreadException in older versions.
I've searched and found that I should use Strict mode in my app, but performance of threads became very bad! when I click parse button it freezes!
can you help me with more better solution?
Call you class like this, it will solve your issue !!
new JSONParser().execute();

layout an XML website on my Android APP

I've been searching for a long time to answer to my simple question but haven't found it yet.
I've just started Android Development and I can't manage to layout this simple XML to the Android App I have just created.
There is my code :
public class MainActivity extends Activity {
private static final String TAG = null;
/** Called when the activity is first created. */
private String getPage() {
String str = null ;
Log.v(TAG, "testentreemethode");
try
{
HttpClient hc = new DefaultHttpClient();
Log.v(TAG, "testnew");
HttpPost post = new HttpPost("http://www.3pi.tf/test.xml");
Log.v(TAG, "testurl");
HttpResponse rp = hc.execute(post);
Log.v(TAG, "testpost");
if(rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
str = EntityUtils.toString(rp.getEntity());
}
}catch(IOException e){
e.printStackTrace();
}
return str;
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView txt = (TextView) findViewById(R.id.textview1);
Log.v(TAG, "test1");
txt.setText(getPage());
Log.v(TAG, "test2");
}
}
As you can see I put some Logcat to see where the "cursor" goes and it can't pass this line:
HttpResponse rp = hc.execute(post);
Can someone help me please?
Network operation cannot be performed on the main thread. Use an AsyncTask to execute it on a seperate thread like this:
public class GetXmlTask extends AsyncTask<Void, Void, String> {
// WeakReferences are used to prevent memory leaks.
// Always use WeakReferences when referencing Views or Activities or a Context from a seperate thread
private final WeakReference<TextView> textViewReference;
private final String url;
public GetXmlTask(TextView textView, String url) {
this.textViewReference = new WeakReference<TextView>(textView);
this.url = url;
}
#Override
protected String doInBackground(Void... params) {
HttpClient hc = new DefaultHttpClient();
Log.v(TAG, "testnew");
HttpPost post = new HttpPost(url);
Log.v(TAG, "testurl");
HttpResponse rp = hc.execute(post);
Log.v(TAG, "testpost");
if(rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
return EntityUtils.toString(rp.getEntity());
}
return "Error";
}
#Override
protected void onPostExecute(String result) {
TextView textView = textViewReference.get();
if(textView != null) {
textView.setText(result);
}
}
}
You can execute the task like this:
GetXmlTask task = new GetXmlTask(textView, "http://www.3pi.tf/test.xml");
task.execute();
In any application you should avoid IO calls on main thread because it is used to handle user events and UI in general. in android doing so causes NetworkOnMainThreadException
Try to move your web calls to a background thread and it should work.
ex
public class MainActivity extends Activity {
TextView textView;
Handler mHandler;
private static final String TAG = null;
/** Called when the activity is first created. */
private String getPage() {
String str = null ;
Log.v(TAG, "testentreemethode");
try
{
HttpClient hc = new DefaultHttpClient();
Log.v(TAG, "testnew");
HttpPost post = new HttpPost("http://www.3pi.tf/test.xml");
Log.v(TAG, "testurl");
HttpResponse rp = hc.execute(post);
Log.v(TAG, "testpost");
if(rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
str = EntityUtils.toString(rp.getEntity());
}
}catch(IOException e){
e.printStackTrace();
}
return str;
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtView = (TextView) findViewById(R.id.textview1);
mHandler = new Handler();
new Thread(){
#Override
public void run(){
final String str = getPage();
mHandler.post(new Runnable(){
#Override
public void run(){
textView.setText(str);
}
});
}
}.start();
Log.v(TAG, "test1");
Log.v(TAG, "test2");
}
}
Please take a look at this tutorial for better understanding of android threadining. tutorial

Connecting and getting data through web API in android

Can anybody please help me with this one. I am trying to get information in a server through web API, I believe, in my code below that I can already connect to the server (because no error appear). But when I am trying to display information that that I get, it display null value. I'm not sure where a forgot something or if my way of parsing it is right.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonGetData = (Button) findViewById(R.id.buttonGetData);
editTextSearchString = (EditText) findViewById(R.id.editTextSearchString);
textViewFirstName = (TextView) findViewById(R.id.textViewFirstName);
textViewLastName = (TextView) findViewById(R.id.textViewLastName);
display = (TextView) findViewById(R.id.display);
spn_Display = (Spinner)findViewById(R.id.spn_Display);
//Setup the Button's OnClickListener
buttonGetData.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Get the data
in = null;
DoPOST mDoPOST = new DoPOST(MainActivity.this, editTextSearchString.getText().toString());
Toast.makeText(getApplicationContext(), editTextSearchString.getText().toString(), 6).show();
mDoPOST.execute("");
buttonGetData.setEnabled(false);
}
});
}
public class DoPOST extends AsyncTask<String, Void, Boolean>
{
Context mContext = null;
String strNameToSearch = "";
//Result data
String strFirstName;
String strLastName;
int intAge;
int intPoints;
Exception exception = null;
DoPOST(Context context, String nameToSearch){
mContext = context;
strNameToSearch = nameToSearch;
}
#Override
protected Boolean doInBackground(String... arg0) {
try{
//Setup the parameters
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("Username", "admin"));
nameValuePairs.add(new BasicNameValuePair("Password", "admin123"));
//Create the HTTP request
HttpParams httpParameters = new BasicHttpParams();
//Setup timeouts
HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
HttpConnectionParams.setSoTimeout(httpParameters, 15000);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
HttpPost httppost = new HttpPost("http://examplesvr4.sample.com:1217/api/subbrands");
HttpGet httpget = new HttpGet("http://examplesvr4.sample.com:1217/api/subbrands");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity);
// Create a JSON object from the request response
JSONObject jsonObject = new JSONObject(result);
//Retrieve the data from the JSON object
strFirstName = jsonObject.getString("SubBrandId");
strLastName = jsonObject.getString("SubBrandName");
}catch (Exception e){
Log.e("ClientServerDemo", "Error:", e);
exception = e;
}
return true;
}
#Override
protected void onPostExecute(Boolean valid){
//Update the UI
textViewFirstName.setText("First Name: " + strFirstName);
textViewLastName.setText("Last Name: " + strLastName);
buttonGetData.setEnabled(true);
if(exception != null){
Toast.makeText(mContext, exception.getMessage(), Toast.LENGTH_LONG).show();
}
}
}

Android: how to use webservices with AsyncTasks

This is my first post on this site, i have a problem with my app, i can't find the reason which my app stops. I am sending a request to Despegar to get a json of the countries but happens these. I would be very greatfull if you could help me. Here is my code:
public class MainActivity extends Activity {
final TextView txtResultado = (TextView) findViewById(R.id.txtResultado);
String JSONRequest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new TareaConexion().execute("http://api.despegar.com/countries");
}
class TareaConexion extends AsyncTask<String, Void, String>{
protected void onPreExecute() {
}
protected String doInBackground(String... urls) {
httpHandler httphandler = new httpHandler();
JSONRequest = httphandler.Post(urls[0]);
return JSONRequest;
}
protected void onProgressUpdate () {
}
protected void onPostExecute() {
txtResultado.setText(JSONRequest);
}
}
and the class httpHandler:
public class httpHandler {
public String Post (String PostURL)
{
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(PostURL);
HttpResponse resp = httpclient.execute(httppost);
HttpEntity ent = resp.getEntity();
String Respuesta = EntityUtils.toString(ent);
return Respuesta;
} catch (Exception e) {
return "error";
}
}
}
can anybody find the reason which do my app stops? what am i doing wrong?
i'm argentinian so excuse me if i make a mistake with the lenguage, ajja. Thanks
Try this code
MyAsyncTask extends AsyncTask<String, Void, HttpResponse>
{
#Override
protected HttpResponse doInBackground(String... param)
{
String url = param[0];
HttpResponse response = null;
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter("http.connection-manager.timeout", 15000);
try {
if (type == Constants.TYPE_POST)
{
HttpPost httppost = new HttpPost(url);
response = httpclient.execute(httppost);
}
else if (type == Constants.TYPE_DELETE)
{
HttpDelete httpdelete = new HttpDelete(url);
response = httpclient.execute(httpdelete);
}
else
{
HttpGet httppost = new HttpGet(url);
response = httpclient.execute(httppost);
}
} catch (ClientProtocolException es)
{
Log.e("x" , es.getMessage());
} catch (IOException e)
{
Log.e("aasx" , e.getMessage());
}
return response;
}
#Override
protected void onPostExecute(HttpResponse response)
{
if (response != null)
{
JSONObject obj = new JSONObject(Utilities.convertStreamToString(response.getEntity().getContent()));
//Whatever you want to do
}
}
}

Android Asynctask post to server error

Am new to android and developing an android app that posts a search item (which is supplied by user into an EditText) to the server when a button is clicked,the item is posted to the server.Am using Asynctask class.I have error with the findViewById(it is undefined).My problem is where to place the onclick method and referncing of the views.Here is the code
public class Server_Post extends AsyncTask<String, Void, String> {
private static final int REGISTRATION_TIMEOUT = 3 * 1000;
private static final int WAIT_TIMEOUT = 30 * 1000;
private final HttpClient httpclient = new DefaultHttpClient();
final HttpParams params = httpclient.getParams();
HttpResponse response;
Button Submit = (Button) findViewById(R.id.submitButton);
EditText textvalue = (EditText)findViewById(R.id.searcheditText);
//Onclick Listener
Submit.setOnClickListener(onClickListener)
private OnClickListener onClickListener = new OnClickListener() {
#Override
public void onClick(final View v) {
switch(v.getId()){
case R.id.submitButton:
break;
}
};
protected void onPreExecute() {
//any code
}
#Override
protected String doInBackground(String... arg0) {
String URL = "url";
String username = "abc";
String password = "xyz";
try {
HttpConnectionParams.setConnectionTimeout(params, REGISTRATION_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, WAIT_TIMEOUT);
ConnManagerParams.setTimeout(params, WAIT_TIMEOUT);
HttpPost httpPost = new HttpPost(URL);
//Any other parameters you would like to set
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username",username));
nameValuePairs.add(new BasicNameValuePair("password",password));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Response from the Http Request
response = httpclient.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
//Check the Http Request for success
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
}
else{
//Closes the connection.
Log.w("HTTP1:",statusLine.getReasonPhrase());
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}catch (Exception e) {
}
return null;
}
protected void onCancelled() {
}
protected void onPostExecute(String content) {
}
private void connecttopostdata() {
Server_Post task = new Server_Post();
task.execute(textvalue.getText().toString());
}
}
the response is in xml and i want to also dispaly the response on listviews.
Thanks in advance.
You need a context of an activity class to get button from findviewbyid . Make a constructor and find your views from there. Like..
// give context from where you are calling your AsyncTask
public Server_Post (Context context)
{
Button Submit = (Button) context.findViewById(R.id.submitButton);
EditText textvalue = (EditText)context.findViewById(R.id.searcheditText);
}

Categories

Resources