close android program Immediately run the app in json - java

hi every body i wrote a program to get data from server and show the data in list view with json
but when i start the app ,app immediately closed.
i checked my manifest and its okay , idont know what should i do , please help me!
Main Activity code:
package com.example.delta.travel;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends ListActivity {
private ProgressDialog pd;
JSONParser jParser=new JSONParser();
ArrayList<HashMap<String,String>> P;
JSONArray s=null;
private final String url="http://192.168.1.4/upload/travel.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new travel().execute();
}
class travel extends AsyncTask<String,String,String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pd=new ProgressDialog(MainActivity.this);
pd.setMessage("login");
pd.show();
}
#Override
protected String doInBackground(String... params) {
List<NameValuePair> parms=new ArrayList<>();
JSONObject json=jParser.makeHTTPRequest(url,"GET",parms);
try {
int t=json.getInt("t");
if(t==1){
s=json.getJSONArray("travel");
for(int i=0;i<s.length();i++){
JSONObject c=s.getJSONObject(i);
String companyname=c.getString("companyname");
String cod=c.getString("cod");
String bign=c.getString("bign");
String stop=c.getString("stop");
String date=c.getString("date");
String time=c.getString("time");
String price=c.getString("price");
HashMap<String,String>map=new HashMap<String,String>();
map.put("companyname",companyname);
map.put("cod",cod);
map.put("bign",bign);
map.put("stop",stop);
map.put("date",date);
map.put("time",time);
map.put("price",price);
P.add(map);
}
}else {
Toast.makeText(MainActivity.this,"No DataFound",Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
pd.dismiss();
runOnUiThread(new Runnable() {
#Override
public void run() {
ListAdapter adapter = new SimpleAdapter(MainActivity.this, P, R.layout.item_list,
new String[]{"companyname", "cod", "bign", "stop", "date", "time", "price"},
new int[]{R.id.companyname, R.id.cod, R.id.bign, R.id.stop, R.id.date, R.id.time1, R.id.price});
setListAdapter(adapter);
}
});
}
}
}
my JSONParser code:
package com.example.delta.travel;
import android.net.http.HttpResponseCache;
import android.util.Log;
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.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.Date;
import java.util.List;
/**
* Created by delta on 5/28/2016.
*/
public class JSONParser {
static InputStream is=null;
static JSONObject jObj=null;
static String json="";
// constructor
public JSONParser(){
}
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHTTPRequest(String url,String method,
List<NameValuePair> params){
//making HTTP request
try{
//check for request method
if(method=="POST"){
// request method is POST
//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();
}else if(method=="GET"){
//request method is GET
DefaultHttpClient httpClient=new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params,"utf-8");
url+="?"+paramString;
HttpGet httpGet=new HttpGet(url);
HttpResponse httpResponse=httpClient.execute(httpGet);
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;
}
}
and my travel.php code:
<?php
$con=mysqli_connect("localhost","root","","travels");
mysqli_set_charset($con,"utf8");
$response=array();
$result=mysqli_query($con,"select * from travel");
if(mysqli_num_rows($result)>0){
while($row=mysqli_fetch_array($result)){
$temp=array();
$temp["companyname"]=$row["companyname"];
$temp["cod"]=$row["cod"];
$temp["bign"]=$row["bign"];
$temp["stop"]=$row["stop"];
$temp["date"]=$row["date"];
$temp["time"]=$row["time"];
$temp["price"]=$row["price"];
$response["travel"]=array();
array_push($response["travel"],$temp);
}
$response["t"]=1;
echo json_encode($response);
}
else{
$response["t"]=0;
$response["message"]="Not Found";
echo json_encode($response);
}
?>

1) Change the code in your JSONParser class with this code. use only this fiction.
public JSONObject makeHTTPRequest(String urlString, String method) {
if(method.equals("POST")){
URL url = null;
try {
url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
StringBuilder sb = new StringBuilder();
while ((output = br.readLine()) != null) {
sb.append(output);
}
conn.disconnect();
json = sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}else if(method.equals("GET")){
URL url = null;
try {
url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
StringBuilder sb = new StringBuilder();
while ((output = br.readLine()) != null) {
sb.append(output);
}
conn.disconnect();
json = sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
e.printStackTrace();
}
return jObj;
}
2) And in MainActivity you have to add P = new ArrayList<>(); in onCreate() method like this.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
P = new ArrayList<>();
new travel().execute();
}
All done it is working at my side. it should definitely work for you too.

Do some changes and see if it works :
new travel().execute(url);
Your AsyncTask :
class travel extends AsyncTask<String,Void,String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pd=new ProgressDialog(MainActivity.this);
pd.setMessage("login");
pd.show();
}
#Override
protected String doInBackground(String... params) {
// List<NameValuePair> parms=new ArrayList<>();
for(urlString in params){
JSONObject json=jParser.makeHTTPRequest(urlString,"GET");
}
//rest is same
In JSONParser Class :
public class JSONParser {
static InputStream is=null;
static JSONObject jObj=null;
static String json="";
// constructor
public JSONParser(){
}
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHTTPRequest(String url,String method){
//making HTTP request
try{
//check for request method
if(method=="POST"){
// request method is POST
//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();
}else if(method=="GET"){
//request method is GET
DefaultHttpClient httpClient=new DefaultHttpClient();
///String paramString = URLEncodedUtils.format(params,"utf-8");
//url+="?"+paramString;
HttpGet httpGet=new HttpGet(url);
HttpResponse httpResponse=httpClient.execute(httpGet);
HttpEntity httpEntity=httpResponse.getEntity();
is=httpEntity.getContent();
}
// Rest is same

Related

Login functionality for andrioid app using mysql

I am coding the login functionality for my android app where it check against my online sql and present the user to the page if login is successful.
But I keep having this error:
E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #5 at these lines: Log.d("Login attempt", json.toString()) and class AttemptLogin extends AsyncTask
How do I solve it? Attached below is the code. Thanks in advance!
JSONParser.java
package com.test.qingyong.test;
/**
* Created by QingYong on 09/08/2015.
*/
import org.apache.http.HttpEntity;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpResponse;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
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.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jsonObj ;
static String json = "";
// default no argument constructor for jsonpaser class
public JSONParser() {
}
public JSONObject getJSONFromUrl(final String url) {
// Making HTTP request
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
// Executing POST request & storing the response from server locally.
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 {
// Create a BufferedReader
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
// Declaring string builder
StringBuilder str = new StringBuilder();
// string to store the JSON object.
String strLine = null;
// Building while we have string !equal null.
while ((strLine = reader.readLine()) != null) {
str.append(strLine + "\n");
}
// Close inputstream.
is.close();
// string builder data conversion to string.
json = str.toString();
} catch (Exception e) {
Log.e("Error", " something wrong with converting result " + e.toString());
}
// Try block used for pasrseing String to a json object
try {
jsonObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("json Parsering", "" + e.toString());
}
// Returning json Object.
return jsonObj;
}
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Make HTTP request
try {
// checking request method
if(method == "POST"){
// now defaultHttpClient object
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();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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 str = new StringBuilder();
String strLine = null;
while ((strLine = reader.readLine()) != null) {
str.append(strLine + "\n");
}
is.close();
json = str.toString();
} catch (Exception e) {
}
// now will try to parse the string into JSON object
try {
jsonObj = new JSONObject(json);
} catch (JSONException e) {
}
return jsonObj;
}
}
Login.java
package com.test.qingyong.test;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Login extends Activity implements OnClickListener{
private EditText user, pass;
private Button bLogin;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "http://powerbankk.16mb.com/test.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
user = (EditText)findViewById(R.id.username);
pass = (EditText)findViewById(R.id.password);
bLogin = (Button)findViewById(R.id.login);
bLogin.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.login:
new AttemptLogin().execute();
// here we have used, switch case, because on Login activity you may //also want to show registration button, so if the user is new ! we can go the //registration activity , menu than this we could also do this without switch //case.
default:
break;
}
}
class AttemptLogin extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Attempting for Login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// here Check for success tag
int success;
String username = user.getText().toString();
String password = pass.getText().toString();
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// checking log for json response
Log.d("Login attempt", json.toString());
// success tag for json
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Successfully Login!", json.toString());
Intent ii = new Intent(Login.this,OtherActivity.class);
finish();
// this finish() method is used to tell android os that we are done with current //activity now! Moving to menu activity
startActivity(ii);
return json.getString(TAG_MESSAGE);
}else{
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* Once the background process is done we need to Dismiss the progress dialog asap
* **/
protected void onPostExecute(String message) {
pDialog.dismiss();
if (message != null){
Toast.makeText(Login.this, message, Toast.LENGTH_LONG).show();
}
}
}
}
Login.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<Button
android:id="#+id/login"
android:layout_width="118dp"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/password"
android:layout_alignRight="#+id/password"
android:layout_below="#+id/password"
android:text="login" />
<EditText
android:id="#+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/password"
android:ems="10"
android:focusable="true"
android:hint="Enter username"
android:imeOptions="actionNext"
/>
<EditText
android:id="#+id/password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/username"
android:layout_centerHorizontal="true"
android:ems="10"
android:hint="Enter Password"
android:imeOptions="actionDone"
/>
</RelativeLayout>
test.php
<?php
mysql_connect("mysql.hostinger.in","username","password");
$db= mysql_select_db("db");
$password=$_POST["password"];
$username=$_POST["username"];
if (!empty($_POST)) {
if (empty($_POST['username']) || empty($_POST['password'])) {
// Create some data that will be the JSON response
$response["success"] = 0;
$response["message"] = "One or both of the fields are empty .";
//die is used to kill the page, will not let the code below to be executed. It will also
//display the parameter, that is the json data which our android application will parse to be //shown to the users
die(json_encode($response));
}
$query = " SELECT * FROM test WHERE username = '$username'and password='$password'";
$sql1=mysql_query($query);
$row = mysql_fetch_array($sql1);
if (!empty($row)) {
$response["success"] = 1;
$response["message"] = "You have been sucessfully login";
die(json_encode($response));
}
else{
$response["success"] = 0;
$response["message"] = "invalid username or password ";
die(json_encode($response));
}
}
else{
$response["success"] = 0;
$response["message"] = " One or both of the fields are empty ";
die(json_encode($response));
}
mysql_close();
?>
Try using Volley or Retrofit .They are faster and error handling is a lot easier than async task.

JAVA ANDROID:Reading Php Json values, Eclipse dont see the error but it doesnt work

Reading Php Json values, Eclipse dont see the error but it doesnt work. Im becoming crazy because it must run, can you help me?
When i execute it nothing happens.
This is the java activity code:
package com.json.php;
import android.app.Activity;
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class JSONExampleActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://iatek.eu/sys/getsms.php");
TextView textView = (TextView)findViewById(R.id.textView1);
try {
HttpResponse response = httpclient.execute(httppost);
String jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
JSONObject obj = new JSONObject(jsonResult);
JSONArray jsonArray = obj.getJSONArray("posts");
/*Para hacer prueba accedo a un registro concreto en este caso el 3*/
JSONObject childJSONObject = jsonArray.getJSONObject(3);
String username = childJSONObject.getString("username");
String sms = childJSONObject.getString("sms");
String fcat = childJSONObject.getString("fcat");
textView.setText(""+sms+"--" + username);
/* para hacer pruebas lo he comentado
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject childJSONObject = jsonArray.getJSONObject(i);
String username = childJSONObject.getString("username");
String sms = childJSONObject.getString("sms");
String fcat = childJSONObject.getString("fcat");
textView.setText(""+sms+"--" + username);
}*/
}
catch (JSONException e) {
e.printStackTrace();
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
e.printStackTrace();
}
return answer;
}
}
and here is the json code into iatek.eu/sys/getsms.php
{"posts":[{"cid":"11","username":"Livi","sms":"ag","fto":"","fcat":"cat"},{"cid":"10","username":"Sumone","sms":"","fto":"","fcat":""},{"cid":"9","username":"R2D2","sms":"dw","fto":"wd","fcat":"wd"},{"cid":"5","username":"Roy","sms":"sa","fto":"sa","fcat":"sa"},{"cid":"12","username":"Charles","sms":"ag","fto":"","fcat":"cat"},{"cid":"13","username":"Clarck","sms":"age","fto":"","fcat":"cat"}]}
can someone tell me where is the mistake?
thanks
You cannot run network operation on the main thread.
Use asyncTask instead.
public class JSONExampleActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new GetSmsTask().execute("http://iatek.eu/sys/getsms.php");
}
private class GetSmsTask extends AsyncTask<String, Void, JSONObject> {
protected JSONObject doInBackground(String... urls) {
JSONObject obj = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url[0]);
HttpResponse response = httpclient.execute(httppost);
String jsonResult = inputStreamToString(response.getEntity()
.getContent()).toString();
obj = new JSONObject(jsonResult);
}
catch (JSONException e) {
e.printStackTrace();
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return obj;
}
protected void onPostExecute(JSONObject obj) {
JSONArray jsonArray = obj.getJSONArray("posts");
JSONObject childJSONObject = jsonArray.getJSONObject(3);
String username = childJSONObject.getString("username");
String sms = childJSONObject.getString("sms");
String fcat = childJSONObject.getString("fcat");
textView.setText(""+sms+"--" + username);
}
}
}
EDIT:
I just ran the code myslef, and I got this
09-13 13:33:59.315: W/System.err(14200): org.json.JSONException:
Unterminated object at character 7551 of {"posts":[{......
This means your JSON is invalid
http://pro.jsonlint.com/ paste your link there you will see the error.
To test that the code is working replace this
String jsonResult = inputStreamToString(response.getEntity()
.getContent()).toString();
with this:
String jsonResult = "{\"posts\":" +
"[{\"cid\":\"11\",\"username\":\"Livi\",\"sms\":\"ag\",\"fto\":\"\",\"fcat\":\"cat\"}," +
" {\"cid\":\"11\",\"username\":\"Livi\",\"sms\":\"ag\",\"fto\":\"\",\"fcat\":\"cat\"}, " +
"{\"cid\":\"11\",\"username\":\"Livi\",\"sms\":\"ag\",\"fto\":\"\",\"fcat\":\"cat\"}," +
"{\"cid\":\"11\",\"username\":\"Livi\",\"sms\":\"ag\",\"fto\":\"\",\"fcat\":\"cat\"}]}";
RESOLVED!!!! ALL ITS PERFECT
HERE IS THE CODE
THANK YOU VERY MUCH meda
package com.json.php;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.widget.EditText;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.json.php.R;
public class JSONExampleActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new GetSmsTask().execute("http://YOURWEBSITE.eu/sys/getsms.php");
}
private class GetSmsTask extends AsyncTask<String, Void, JSONObject> {
protected JSONObject doInBackground(String... urls) {
JSONObject obj = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urls[0]);
HttpResponse response = httpclient.execute(httppost);
/* String jsonResult = "{\"posts\":" + //FOR TESTS
"[{\"cid\":\"11\",\"username\":\"Livi\",\"sms\":\"ag\",\"fto\":\"\",\"fcat\":\"cat\"}," +
" {\"cid\":\"11\",\"username\":\"Livi\",\"sms\":\"ag\",\"fto\":\"\",\"fcat\":\"cat\"}, " +
"{\"cid\":\"11\",\"username\":\"Livi\",\"sms\":\"ag\",\"fto\":\"\",\"fcat\":\"cat\"}," +
"{\"cid\":\"11\",\"username\":\"Livi\",\"sms\":\"ag\",\"fto\":\"\",\"fcat\":\"cat\"}]}";
*/
String jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
obj = new JSONObject(jsonResult);
}
catch (JSONException e) {
e.printStackTrace();
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return obj;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
e.printStackTrace();
}
return answer;
}
protected void onPostExecute(JSONObject obj) {
JSONArray jsonArray;
try {
jsonArray = obj.getJSONArray("posts");
JSONObject childJSONObject = jsonArray.getJSONObject(3);
String username = childJSONObject.getString("username");
String sms = childJSONObject.getString("sms");
String fcat = childJSONObject.getString("fcat");
TextView textView = (TextView) findViewById(R.id.textView1);
textView.setText(""+sms+"--" + username);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

Send JSON from Java to PHP through Post

I am doing an Android program that is supposed to send data from the tablet to a PHP Web Service. The code for sending the JSON:
package com.example.shvalidation;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
public class MainMenuScreen extends Activity {
//JSON Variables
JSONParser jsonParser = new JSONParser();
String pid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_menu_layout);
new TestThread().execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_menu_layout, menu);
return true;
}
public void PlantToDome(View view) {
Intent intent = new Intent(this, SelectLocationScreen.class);
startActivity(intent);
}
//Código del Web Service
public class TestThread extends AsyncTask<Void, Void, Void> {
ProgressDialog dialog;
protected void onPreExecute() {
dialog = ProgressDialog.show(MainMenuScreen.this, "Loading", "Loading data, please wait..");
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
protected Void doInBackground(Void...args0) {
try {
HttpClient client = new DefaultHttpClient();
HttpResponse response;
HttpPost post = new HttpPost("http://192.168.1.101:8080/GetBook.php");
JSONObject holder = new JSONObject();
JSONObject euid = new JSONObject();
euid.put("euid", 1);
holder.accumulate("euids", euid);
euid.put("euid", 2);
holder.accumulate("euids", euid);
post.setHeader("json", holder.toString());
StringEntity se = new StringEntity(holder.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
if (response != null) {
InputStream in = response.getEntity().getContent();
String a = convertStreamToString(in);
Log.i("Read from Server", a);
}
} catch (Exception e) {
Log.d("error", e.toString());
}
return null;
}
protected void onPostExecute(Void unused) {
dialog.dismiss();
}
}
}
The PHP Web Service:
<?php
ob_start();
var_dump(json_decode(file_get_contents('php://input')));
$out = ob_get_contents();
ob_end_clean();
$f = fopen('out.txt', 'w+');
fwrite($f, html_entity_decode($out));
fclose($f);
?>
I have tried different methods for getting the JSON, but none of them have worked for me. Maybe the fine people of StackOverflow can help me out with this, as they always have for every other problem that I've had.
From the comments section, it appears you only want the JSON being sent to your PHP script. Normally, you post POST this to PHP, and extract it:
<?php
print_r($_POST);
$json_string = $_POST['message'];
$json = json_decode($json_string);
print_r($json);
?>
And then a small client example:
public static void main(String[] args) {
String json = "{\"message\":\"This is a message\"}";
HttpClient httpClient = new DefaultHttpClient();
try {
HttpPost request = new HttpPost("http://somesite.com/test.php");
StringEntity params =new StringEntity("message=" + json);
request.addHeader("content-type", "application/x-www-form-urlencoded");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
// handle response here...
System.out.println(org.apache.http.util.EntityUtils.toString(response.getEntity()));
org.apache.http.util.EntityUtils.consume(response.getEntity());
} catch (Exception ex) {
// handle exception here
} finally {
httpClient.getConnectionManager().shutdown();
}
}
The output of this is:
Array
(
[message] => {"message":"This is a message"}
)
stdClass Object
(
[message] => This is a message
)

How to extract the URL following an HTTPPost in Android

I'm scratching my head at this problem that I can't seem to figure out. What I'm trying to do is extract the URL following the HTTPpost. This will allow me to go through the Oauth process.
Currently I'm extracting the whole website into my entity.
For example: The data will be posted to https://mysite.com/login and will redirect after the post to https://mysite.com/dashboard?code=3593085390859082093720
How does one extract the url?
If you need any more information or can direct me in the right direction, all is appreciated! Thank you!
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.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.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class LoginActivity extends Activity implements OnClickListener {
Button ok,back,exit;
TextView result;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
// Login button clicked
ok = (Button)findViewById(R.id.submit);
ok.setOnClickListener(this);
result = (TextView)findViewById(R.id.result);
}
public void postLoginData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://mysite.com/login");
try {
// Add user name and password
EditText uname = (EditText)findViewById(R.id.username);
String username = uname.getText().toString();
EditText pword = (EditText)findViewById(R.id.password);
String password = pword.getText().toString();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("pseudonym_session[unique_id]", username));
nameValuePairs.add(new BasicNameValuePair("pseudonym_session[password]", password));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
Log.w("CANVAS", "Execute HTTP Post Request");
HttpResponse response = httpclient.execute(httppost);
String str = inputStreamToString(response.getEntity().getContent()).toString();
Log.w("CANVAS", str);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String ResponseBody = httpclient.execute(httppost, responseHandler);
Intent intent = new Intent(getBaseContext(), DashboardActivity.class);
startActivity(intent);
if(str.toString().equalsIgnoreCase("true"))
{
Log.w("CANVAS", "TRUE");
result.setText("Login successful");
}else
{
Log.w("CANVAS", "FALSE");
result.setText(ResponseBody);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private StringBuilder inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Return full string
return total;
}
#Override
public void onClick(View view) {
if(view == ok){
postLoginData();
}
}
}
if you set a redirect handler, you can get back from the response the location the server's sending you to. here's a snippet of code I was just playing with... (and I should point out, if you DON'T set a redirect handler, you'll just get redirected to the final destination, which might be the login screen itself)
DefaultHttpClient htc = getHttpClient();
htc.setRedirectHandler(new RedirectHandler() {
#Override
public boolean isRedirectRequested(HttpResponse response, HttpContext context)
{
Log.d(TAG, "isRedirectRequested, response: " + response.toString());
return false;
}
#Override
public URI getLocationURI(HttpResponse response, HttpContext context)
throws ProtocolException
{
Log.d(TAG, "getLocationURI, response: " + response.toString());
return null;
}
});
HttpResponse resp = null;
StringBuilder out = new StringBuilder();
try
{
HttpGet get = new HttpGet(spec);
resp = htc.execute(get);
for (Header hdr : resp.getAllHeaders())
Log.d(TAG, "header " + hdr.getName() + " -> " + hdr.getValue());
...
}
catch (Exception e)
{
Log.e(TAG, "Error connecting to " + spec, e);
return null;
}
Search for a substring in the HttpPost url

Downloading Tweets via JSON feed code not working

I'm building my first android app - something that will display my tweets in a list.
I managed to get the app working earlier, but the tweets would sometimes take a long time to download, and the app would become unresponsive or crash.
I decided to add a thread to the app so the it wouldn't become unresponsive, but now it doesn't work at all :/
Does anyone know what's wrong? It's only my third day of learning java, and I can't seem to figure out what the problem is here.
Here's the code:
package com.app.first;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
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.JSONArray;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
public class Twitter extends ListActivity {
public ProgressDialog pd = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// Show the ProgressDialog on this thread
pd = ProgressDialog.show(this, "Working..", "Downloading Data...",
true, false);
new LoadTwitterFeed().execute();
}
public class LoadTwitterFeed extends AsyncTask<String, Integer, String> {
String tweets[] = new String[9];
public String readTwitterFeed() {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(
"https://api.twitter.com/1/statuses/user_timeline.json?screen_name=jjmpsp&include_rts=false&count=10");
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
Log.e(ParseJSON.class.toString(), "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return builder.toString();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String readTwitterFeed = readTwitterFeed();
try {
JSONArray jsonArray = new JSONArray(readTwitterFeed);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
tweets[i] = jsonObject.getString("text").toString();
}
} catch (Exception e) {
e.printStackTrace();
}
setListAdapter(new ArrayAdapter<String>(Twitter.this,
android.R.layout.simple_list_item_1, tweets));
return null;
}
#Override
protected void onPostExecute(String result) {
// what to do when the task ends.
pd.hide();
}
}
}
set this code in onPostExecute
setListAdapter(new ArrayAdapter<String>(Twitter.this,
android.R.layout.simple_list_item_1, tweets));

Categories

Resources