I know this is a question that has been asked before, and I looked through the answers on those and none seemed to be working.
This is the logcat output:
05-01 16:52:42.748: E/AndroidRuntime(10046): FATAL EXCEPTION: Thread-53419
05-01 16:52:42.748: E/AndroidRuntime(10046): Process: com.ritvik.weaselyclock, PID: 10046
05-01 16:52:42.748: E/AndroidRuntime(10046): java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
05-01 16:52:42.748: E/AndroidRuntime(10046): at android.content.ContextWrapper.getPackageName(ContextWrapper.java:131)
05-01 16:52:42.748: E/AndroidRuntime(10046): at android.content.ComponentName.<init>(ComponentName.java:77)
05-01 16:52:42.748: E/AndroidRuntime(10046): at android.content.Intent.<init>(Intent.java:4006)
05-01 16:52:42.748: E/AndroidRuntime(10046): at com.ritvik.utils.HTTPUtils.procResp(HTTPUtils.java:154)
05-01 16:52:42.748: E/AndroidRuntime(10046): at com.ritvik.utils.HTTPUtils$1.run(HTTPUtils.java:57)
05-01 16:52:42.748: E/AndroidRuntime(10046): at java.lang.Thread.run(Thread.java:818)
The error is coming from this line:
HTTPUtils.this.startActivity(new Intent(this, MainActivity.class));
HTTPUtils.java:57 is this code:
httpUtils.procResp(responseBody);
httpUtils is the instance of HTTPUtils.java
Any help appreciated. Thanks in advance.
UPDATE:
This is the rest of the HTTPUtils code.
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.ParseException;
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.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.ritvik.weaselyclock.MainActivity;
public class HTTPUtils extends Activity{
static Context context;
public static HTTPUtils httpUtils = new HTTPUtils();
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
MainActivity mainActivity = new MainActivity();
context = mainActivity.context;
}
public static void HTTPPostExec(final String url, final List<NameValuePair> nameValuePairs)
{
Thread t = new Thread(new Runnable() {
#Override
public void run() {
String responseBody = "";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = null;
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);
responseBody = EntityUtils.toString(response
.getEntity());
} catch (ParseException | IOException e) {
e.printStackTrace();
}
Log.d("Server Response", responseBody);
httpUtils.procResp(responseBody);
}
});
t.start();
}
public static void HTTPPostExec(final String url, final String msg)
{
Thread t = new Thread(new Runnable() {
#Override
public void run() {
String responseBody = "";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = null;
try
{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("msg", msg));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);
responseBody = EntityUtils.toString(response.getEntity());
}
catch (ParseException | IOException e)
{
e.printStackTrace();
}
Log.d("Server Response", responseBody);
httpUtils.procResp(responseBody);
}
});
t.start();
}
public static void GetExec (final String url, final List<NameValuePair> nameValuePairs){
Thread t = new Thread(new Runnable() {
#Override
public void run() {
String responseBody = "";
HttpClient Client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url + "?" + nameValuePairs.toString());
HttpResponse response = null;
try
{
response = Client.execute(httpget);
responseBody = EntityUtils.toString(response.getEntity());
Log.d("Server Response", responseBody);
httpUtils.procResp(responseBody);
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
t.start();
}
public static void GetExec (final String url, final String nameValuePairs){
Thread t = new Thread(new Runnable() {
#Override
public void run() {
String responseBody = "";
HttpClient Client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url + "?" + nameValuePairs);
HttpResponse response = null;
try
{
response = Client.execute(httpget);
responseBody = EntityUtils.toString(response.getEntity());
Log.d("Server Response", responseBody);
httpUtils.procResp(responseBody);
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
t.start();
}
public void procResp(String msg) {
JSONObject JSON = null;
String type = "";
try {
JSON = new JSONObject(msg);
type = JSON.getString("type");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (type.equals("ru_001")) {
HTTPUtils.this.startActivity(new Intent(this, MainActivity.class));
Toast.makeText(this, "Registration successful", Toast.LENGTH_LONG).show();
}
else if (type.equals("ru_002")) {
Toast.makeText(((MainActivity)context), "Registration successfully updated", Toast.LENGTH_LONG).show();
}
else if ( type.equals("ru_101") || type.equals("ru_102")
|| type.equals("ru_103") || type.equals("ru_201")
|| type.equals("ru_202") || type.equals("ru_203")
|| type.equals("ru_204") || type.equals("ru_205")
|| type.equals("ru_206") || type.equals("ru_207")
|| type.equals("ru_208") || type.equals("ru_209")
|| type.equals("ru_210") || type.equals("ru_211")
|| type.equals("jr_201") || type.equals("jr_202")
|| type.equals("jr_203") || type.equals("jr_204")
|| type.equals("jr_205") || type.equals("jr_206")
|| type.equals("jr_207") || type.equals("jr_208")
|| type.equals("jr_209") || type.equals("id_201")
|| type.equals("id_202") || type.equals("id_203")
|| type.equals("id_204") || type.equals("id_205")
|| type.equals("id_206") || type.equals("id_207")
|| type.equals("id_208") || type.equals("sm_201")
|| type.equals("sm_202") || type.equals("sm_203")
|| type.equals("sm_204") || type.equals("sm_205")
|| type.equals("sm_206") || type.equals("sm_207")
|| type.equals("sm_208") || type.equals("sm_209")
|| type.equals("sm_210")) {
try {
Log.e("Server error:", JSON.getString("error"));
Toast.makeText(context, "Server error: " + JSON.getString("error"), Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
else if (type.equals("jr_101") || type.equals("jr_102")) {
try {
Toast.makeText(context, JSON.getString("action"), Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
else if (type.equals("jr_301") || type.equals("jr_302")) {
try {
Toast.makeText(context, "You have been " + JSON.getString("action") + "by group" + JSON.getString("group") , Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
else if (type.equals("id_101")) {
try {
JSONArray members = JSON.getJSONArray("members");
JSONUtils.writeJSON("com.ritvik.weaselyclock.MEMBERS", context, members, "members");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Excuse the long if-statement and the bad coding, I know it's horrible...
UPDATE 2: I just moved all the code into one activity and it fixed it. Thanks for the help, though.
First of all, You are creating the instance of the Activity inside itself. HTTPUtils is itself an activity, so don't do this inside it :
public static HTTPUtils httpUtils = new HTTPUtils();
And try to modify like this to start Activity.
startActivity(new Intent(HTTPUtils.this, MainActivity.class));
Related
i was trying to create an online apps. I would like to send a string from my apps to my PHP script, but it ended up with the php doesn't receive any string from my apps, which means the PhP will echo back NULL. I have been doing research online and searching for solution, but none of them worked.
Below is my MainActivity.java code:
package my.com.tutionathome.calvinlau.testserver;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
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 {
Button b;
EditText et;
TextView tv;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button)findViewById(R.id.Button01);
et= (EditText)findViewById(R.id.EditText01);
tv= (TextView)findViewById(R.id.tv);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final ProgressDialog p = new ProgressDialog(v.getContext()).show(v.getContext(),"Waiting for Server", "Accessing Server");
Thread thread = new Thread()
{
#Override
public void run() {
try{
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://10.0.0.2/my_folder_inside_htdocs/connection.php"); // make sure the url is correct.
//add your data
nameValuePairs = new ArrayList<NameValuePair>(1);
// Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
nameValuePairs.add(new BasicNameValuePair("username",et.getText().toString().trim())); // $"username" = $_POST['username'];
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
response=httpclient.execute(httppost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
System.out.println("Response : " + response);
runOnUiThread(new Runnable() {
public void run() {
p.dismiss();
tv.setText("Response from PHP : " + response);
}
});
}catch(Exception e){
runOnUiThread(new Runnable() {
public void run() {
p.dismiss();
}
});
System.out.println("Exception : " + e.getMessage());
}
}
};
thread.start();
}
});
}
}
And my php code:
<?php
// put your code here
$hostname_localhost ="localhost";
$database_localhost ="android";
$username_localhost ="root";
$password_localhost ="";
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_localhost, $localhost);
$username = $_POST['username'];
$password = $_POST['password'];
$query_search = "select Email, Username from tblmember where Username = '".$username."' AND Email = '".$password. "'";
$query_exec = mysql_query($query_search) or die(mysql_error());
$rows = mysql_num_rows($query_exec);
if($username == NULL){
echo "NULL";
}else{
echo $username;
}
?>
This is my Android Manifest :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="my.com.tutionathome.calvinlau.testserver">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<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>
There are a bunch of libraries to facilitate this, saving many lines of code, i particularly suggest retrofit.
Try this Code.
AysncyTask
private class AysncyTask extends AsyncTask<Void,Void,Void>
{
private ProgressDialog regDialog=null;
#Override
protected void onPreExecute()
{
super.onPreExecute();
regDialog=new ProgressDialog(this);
regDialog.setTitle(getResources().getString(R.string.app_name));
regDialog.setMessage(getResources().getString(R.string.app_pleasewait));
regDialog.setIndeterminate(true);
regDialog.setCancelable(true);
regDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try
{
new Thread(new Runnable() {
#Override
public void run() {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username",
et.getText().toString().trim()));
postParameters.add(new BasicNameValuePair("password",
etpass.getText().toString().trim()));
String response = null;
try {
response = SimpleHttpClient
.executeHttpPost("http://10.0.0.2/my_folder_inside_htdocs/connection.php",
postParameters);
res = response.toString();
return res;
} catch (Exception e) {
e.printStackTrace();
errorMsg = e.getMessage();
}
}
}).start();
try {
Thread.sleep(3000);
// error.setText(resp);
if (null != errorMsg && !errorMsg.isEmpty()) {
}
} catch (Exception e) {
}
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
if(regDialog!=null)
{
regDialog.dismiss();
//do you code here you want
}
// do what u do
}
SimpleHttpClient.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
public class SimpleHttpClient {
/** The time it takes for our client to timeout */
public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
/** Single instance of our HttpClient */
private static HttpClient mHttpClient;
/**
* Get our single instance of our HttpClient object.
*
* #return an HttpClient object with connection parameters set
*/
private static HttpClient getHttpClient() {
if (mHttpClient == null) {
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}
public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static String executeHttpatch(String url, ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* Performs an HTTP GET request to the specified url.
*
* #param url The web address to post the request to
* #return The result of the request
* #throws Exception
*/
public static String executeHttpGet(String url) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
I'm developing my android app for a conference. In, my login page I printed an error message when no internet connection. but, the app crashes when no internet connection and following error message display in logcat.
I followed many questions from stack overflow and may be I can't understand, I couldn't find my answer.
08-19 10:01:21.840
8931-9124/com.NICT.nict E/AndroidRuntime﹕ FATAL EXCEPTION: Thread-691
java.lang.RuntimeException: Can't create handler inside thread that hasnot called Looper.prepare()
at android.os.Handler.<init>(Handler.java:205)
at android.os.Handler.<init>(Handler.java:119)
atandroid.widget.Toast$TN.<init>(Toast.java:325)
atandroid.widget.Toast.<init>(Toast.java:91)
atandroid.widget.Toast.makeText(Toast.java:239)
at com.NICT.nict.services.MessageHandler.showMessage(MessageHandler.java:9)
at com.NICT.nict.LoginActivity$1$1.run(LoginActivity.java:117)
at java.lang.Thread.run(Thread.java:838)
Here is my login activity
package com.NICT.nict;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import com.NICT.nict.WorkShopActivity.HttpAsyncTask;
import com.NICT.nict.services.EmailValidator;
import com.NICT.nict.services.MessageHandler;
import com.NICT.nict.services.ServiceHandler;
public class LoginActivity extends Activity {
public final static String URL = "http://demo.et.lk/nitcapi/api/login";
public static String Uid;
private Button loginBtn;
private EditText codeEdit;
private EditText nameEdit;
private EditText emailEdit;
private ServiceHandler sh = new ServiceHandler();
private boolean errorStatus;
private ProgressBar spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loginBtn = (Button) findViewById(R.id.loginBtn);
codeEdit = (EditText) findViewById(R.id.codeEdit);
nameEdit = (EditText) findViewById(R.id.nameEdit);
emailEdit = (EditText) findViewById(R.id.emailEdit);
spinner = (ProgressBar) findViewById(R.id.progressBar1);
spinner.setVisibility(View.GONE);
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!ServiceHandler.isOnline(getApplicationContext())) {
MessageHandler.showMessage("You are not online.",
getApplicationContext());
}
new Thread(new Runnable() {
public void run() {
String code = codeEdit.getText().toString();
String email = emailEdit.getText().toString();
String name = nameEdit.getText().toString();
if (code.length() == 0) {
runOnUiThread(new Runnable() {
public void run() {
MessageHandler.showMessage(
"Please Enter the app code",
getApplicationContext());
errorStatus = true;
}
});
;
} else if (name.length() == 0) {
runOnUiThread(new Runnable() {
public void run() {
MessageHandler.showMessage(
"Please Enter Your Name",
getApplicationContext());
errorStatus = true;
}
});
;
} else if (email.length() == 0) {
runOnUiThread(new Runnable() {
public void run() {
MessageHandler.showMessage(
"Please Enter Your Email",
getApplicationContext());
errorStatus = true;
}
});
;
}
EmailValidator emailValidator = new EmailValidator();
if(!emailValidator.validate(email)){
runOnUiThread(new Runnable() {
public void run() {
MessageHandler.showMessage(
"Invalid Email",
getApplicationContext());
errorStatus = true;
}
});
;
}
String jsonStr = null;
if (!errorStatus) {
if (!ServiceHandler.isOnline(getApplicationContext())) {
MessageHandler.showMessage("You are not online.",
getApplicationContext());
} else {
ConnectivityManager conMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
// notify user you are online
try{
runOnUiThread(new Runnable() {
public void run() {
spinner.setVisibility(View.VISIBLE);
}
});
;
jsonStr = sh.makeServiceCall(URL + "/" + code + "/"
+ name + "/" + email, ServiceHandler.GET);
System.out.println(URL + "/" + code + "/" + name + "/"
+ email);
}
catch (Exception e){
spinner.setVisibility(View.GONE);
runOnUiThread(new Runnable() {
public void run() {
MessageHandler.showMessage("You are not online.",
getApplicationContext());
}
});
;
}
}
if (jsonStr != null) {
String status = "";
String msg = "";
try {
JSONObject jsonObj = new JSONObject(jsonStr);
runOnUiThread(new Runnable() {
public void run() {
spinner.setVisibility(View.GONE);
}
});
;
if (jsonObj != null
&& jsonObj.has("status")) {
status = jsonObj.getString("status");
msg = jsonObj.getString("message");
if(jsonObj.has("uid"))
Uid = jsonObj.getString("uid");
System.out.println(jsonObj);
if (status.equals("OK")) {
Intent myIntent = new Intent(
getBaseContext(),
MainMenuActivity.class);
startActivityForResult(myIntent, 0);
} else if (status.equals("ERROR")) {
final String errorMsg = msg;
runOnUiThread(new Runnable() {
public void run() {
MessageHandler
.showMessage(
errorMsg,
getApplicationContext());
}
});
;
} else {
runOnUiThread(new Runnable() {
public void run() {
MessageHandler
.showMessage(
"Oops..! something wrong with the service. Please try again Later.",
getApplicationContext());
}
});
;
}
}
} catch (Exception e) {
System.out
.println("Creation of json object failed");
}
}
}
}
}).start();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
}
Here is my serviceHandler.
package com.NICT.nict.services;
import java.io.IOException;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/**
* Making service call
*
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/**
* Making service call
*
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
public static boolean isOnline(Context ctx) {
ConnectivityManager cm;
NetworkInfo info = null;
try {
cm = (ConnectivityManager) ctx
.getSystemService(Context.CONNECTIVITY_SERVICE);
info = cm.getActiveNetworkInfo();
} catch (Exception e) {
e.printStackTrace();
}
return (info!=null&&!info.equals(null));
}
}
add this following snippet in your if condition::
if (!ServiceHandler.isOnline(getApplicationContext())) {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(
new Runnable()
{
#Override
public void run()
{
MessageHandler.showMessage("You are not online.",
getApplicationContext());
}
}
);
}
Try this.when you see runtimeException due to Looper not prepared before handler.
Handler handler = new Handler(Looper.getMainLooper());
From Android Docs:
LOOPER
Class used to run a message loop for a thread. Threads by default do
not have a message loop associated with them; to create one, call
prepare() in the thread that is to run the loop, and then loop() to
have it process messages until the loop is stopped.
Looper.getMainLooper()
Returns the application's main looper, which
lives in the main thread of the application.
I hope it helps!
Android basically works on two thread types namely UI thread and background thread.
Try this,
activity.runOnUiThread(new Runnable() {
public void run() {
//run your code here.....
}
});
I have an application hosted on "heroku". It has this method you call it via a get and it will respond with a "Json code"
public static Result renderManga(int id) {
Manga m = Manga.find.byId(id);
if (m != null) {
return ok(Json.toJson(m));
} else
return null;
}
}
route file
GET /srvc/manga/:id controllers.Services.renderManga(id:Integer)
now my android code
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet("https://boku-no-manga.herokuapp.com/srvc/manga/5"));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
String responseString = out.toString();
EditText res = (EditText) findViewById(R.id.result);
res.setText(responseString);
Log.i("JSONmymanga",responseString);
out.close();
} else {
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (Exception e) {}
I want to receive that JSON code sent by my play app and work with it in my android app.
Try this code,
import java.io.IOException;
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.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
public class ServerTest extends Activity {
private String TAG = "test";
private String url = "https://boku-no-manga.herokuapp.com/srvc/manga/5";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new Download().execute();
}
public class Download extends AsyncTask<Void, Void, String>{
#Override
protected String doInBackground(Void... params) {
String out = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
final HttpParams httpParameters = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
HttpConnectionParams.setSoTimeout(httpParameters, 15000);
HttpGet httpPost = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
out = EntityUtils.toString(httpEntity, HTTP.UTF_8);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return out;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.e(TAG, result);
}
}
}
Also make sure you have added this to manifest,
<uses-permission android:name="android.permission.INTERNET" />
I need to upload an xml file from my android application to a remote host. I found this code and get the library from here. but I got this error:
02-17 22:06:41.144: E/AndroidRuntime(21644): FATAL EXCEPTION: main
02-17 22:06:41.144: E/AndroidRuntime(21644): java.lang.NoClassDefFoundError: org.apache.http.entity.mime.HttpMultipart
02-17 22:06:41.144: E/AndroidRuntime(21644): at org.apache.http.entity.mime.MultipartEntity.<init>(MultipartEntity.java:77)
02-17 22:06:41.144: E/AndroidRuntime(21644): at org.apache.http.entity.mime.MultipartEntity.<init>(MultipartEntity.java:100)
and here is my upload method.
private void upload(String filepath)
{
try
{
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost("http://myurl.com/");
File file = new File(filepath);
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, "application/xml");
mpEntity.addPart("userfile", cbFile);
httppost.setEntity(mpEntity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
}
catch(Exception e)
{
e.printStackTrace();
}
}
Am I using a bad mime type or download wrong library?
Any solution?
Thanks
I found a new example here that upload an image to php server using php script. so I changed it for uploading xml file.
Android Activity: UploadXmlFile.java
import java.io.IOException;
import java.io.InputStream;
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.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class UploadXmlFile extends Activity {
InputStream inputStream;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
String the_string_response;
int contentLength;
String res = "";
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_upload_image);
// create xml content
String xmldata="<?xml version=\"1.0\" encoding=\"UTF-8\"?><langs><lan><id>1</id><name>java</name></lan><lan><id>2</id><name>c++</name></lan><lan><id>3</id><name>python</name></lan><lan><id>4</id><name>php</name></lan></langs>";
nameValuePairs.add(new BasicNameValuePair("xmldata",xmldata));
nameValuePairs.add(new BasicNameValuePair("filename","myfile.xml"));
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://your-url.com/upload_xml_file.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
the_string_response = convertResponseToString(response);
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(UploadXmlFile.this, "Response " + the_string_response, Toast.LENGTH_LONG).show();
}
});
}catch(final Exception e){
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(UploadXmlFile.this, "Error " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
Log.d("Error in http connection ",e.toString());
}
}
});
t.start();
}
public String convertResponseToString(HttpResponse response) throws IllegalStateException, IOException{
StringBuffer buffer = new StringBuffer();
inputStream = response.getEntity().getContent();
contentLength = (int) response.getEntity().getContentLength(); //getting content length…..
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(UploadXmlFile.this, "contentLength : " + contentLength, Toast.LENGTH_LONG).show();
}
});
if (contentLength < 0){
}
else{
byte[] data = new byte[512];
int len = 0;
try
{
while (-1 != (len = inputStream.read(data)) )
{
buffer.append(new String(data, 0, len)); //converting to string and appending to stringbuffer…..
}
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
inputStream.close(); // closing the stream…..
}
catch (IOException e)
{
e.printStackTrace();
}
res = buffer.toString(); // converting stringbuffer to string…..
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(UploadXmlFile.this, "Result : " + res, Toast.LENGTH_LONG).show();
}
});
//System.out.println("Response => " + EntityUtils.toString(response.getEntity()));
}
return res;
}
}
PHP file: upload_xml_file.php
<?php
$base=$_REQUEST['xmldata'];
$fname=$_REQUEST['filename'];
header("Content-Type: text/xml; charset=utf-8");
$file = fopen($fname, 'wb');
fwrite($file, $base);
fclose($file);
echo 'Image upload complete!!, Please check your php file directory……';
?>
upload the php file on server and set INTERNET permission for android application.
Hope help for others.
I am trying to get a response from a service (the response comes in json).
I made my checks if the device is connected and now I need to make the http request to the service. I found out on other questions that I have to use a background thread but I am not sure I got a working sample.
So I need to find out how I can make a connection to a given uri and read the response.
My service needs to get a content header application/json in orderto return a json, so before the request I need to set this header as well.
Thank you in advance
UPDATE
package com.example.restfulapp;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.provider.Settings;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.ExecutionException;
public class MainActivity extends Activity {
private int code = 0;
private String value = "";
private ProgressDialog mDialog;
private Context mContext;
private String mUrl ="http://192.168.1.13/myservice/upfields/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (!isOnline())
{
displayNetworkOption ("MyApp", "Application needs network connectivity. Connect now?");
}
try {
JSONObject s = getJSON(mUrl);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
public class Get extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... arg) {
String linha = "";
String retorno = "";
mDialog = ProgressDialog.show(mContext, "Please wait", "Loading...", true);
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(mUrl);
try {
HttpResponse response = client.execute(get);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Ok
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
while ((linha = rd.readLine()) != null) {
retorno += linha;
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return retorno;
}
#Override
protected void onPostExecute(String result) {
mDialog.dismiss();
}
}
public JSONObject getJSON(String url) throws InterruptedException, ExecutionException {
setUrl(url);
Get g = new Get();
return createJSONObj(g.get());
}
private void displayNetworkOption(String title, String message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder
.setTitle(title)
.setMessage(message)
.setPositiveButton("Wifi", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
}
})
.setNeutralButton("Data", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
startActivity(new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS));
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
return;
}
})
.show();
}
private boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
}
This throws errors:
Gradle: cannot find symbol method setUrl(java.lang.String)
Gradle: cannot find symbol method createJSONObj(java.lang.String)
After derogatory responses from EvZ who think that he was born knowing everything, I ended up with a subclass MyTask that I call like this inside the onCreate of my Activity.
new MyTask().execute(wserviceURL);
private class MyTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
URL myurl = null;
try {
myurl = new URL(urls[0]);
} catch (MalformedURLException e) {
e.printStackTrace();
}
URLConnection connection = null;
try {
connection = myurl.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
connection.setConnectTimeout(R.string.TIMEOUT_CONNECTION);
connection.setReadTimeout(R.string.TIMEOUT_CONNECTION);
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestProperty("Content-Type", getString(R.string.JSON_CONTENT_TYPE));
int responseCode = -1;
try {
responseCode = httpConnection.getResponseCode();
} catch (SocketTimeoutException ste) {
ste.printStackTrace();
}
catch (Exception e1) {
e1.printStackTrace();
}
if (responseCode == HttpURLConnection.HTTP_OK) {
StringBuilder answer = new StringBuilder(100000);
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
String inputLine;
try {
while ((inputLine = in.readLine()) != null) {
answer.append(inputLine);
answer.append("\n");
}
} catch (IOException e) {
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
httpConnection.disconnect();
return answer.toString();
}
else
{
//connection is not OK
httpConnection.disconnect();
return null;
}
}
#Override
protected void onPostExecute(String result) {
String userid = null;
String username = null;
String nickname = null;
if (result!=null)
{
try {
//do read the JSON here
} catch (JSONException e) {
e.printStackTrace();
}
}
//stop loader dialog
mDialog.dismiss();
}
}
lory105's answer guided me to somewhere near the answer, thanx.
here is an example of how to process the HTTP response and convert to JSONObject:
/**
* convert the HttpResponse into a JSONArray
* #return JSONObject
* #param response
* #throws IOException
* #throws IllegalStateException
* #throws UnsupportedEncodingException
* #throws Throwable
*/
public static JSONObject processHttpResponse(HttpResponse response) throws UnsupportedEncodingException, IllegalStateException, IOException {
JSONObject top = null;
StringBuilder builder = new StringBuilder();
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
String decoded = new String(builder.toString().getBytes(), "UTF-8");
Log.d(TAG, "decoded http response: " + decoded);
JSONTokener tokener = new JSONTokener(Uri.decode(builder.toString()));
top = new JSONObject(tokener);
} catch (JSONException t) {
Log.w(TAG, "<processHttpResponse> caught: " + t + ", handling as string...");
} catch (IOException e) {
Log.e(TAG, "caught: " + e, e);
} catch (Throwable t) {
Log.e(TAG, "caught: " + t, t);
}
return top;
}
From Android 3+, the http connections must be done within a separate thread. Android offers a Class named AsyncTask that help you do it.
Here you can find a good example of an AsyncTask that performs an http request and receives a JSON response.
Remember that in the doInBackgroud(..) method you CAN'T modify the UI such as to launch a Toast, to change activity or others. You have to use the onPreExecute() or onPostExecute() methods to do this.
ADD
For the mDialog and mContext variables, add the code below, and when you create the JSONTask write new JSONTask(YOUR_ACTIVITY)
public abstract class JSONTask extends AsyncTask<String, Void, String> {
private Context context = null;
ProgressDialog mDialog = new ProgressDialog();
public JSONTask(Context _context){ context=_context; }
..