I have the following code and i like to add my parsed JSON image from URL to my ImageView I don't know how to do it and my code is the following (I get responce and the other data go the desired TextViews):
DisplaySearchResultsActivity.java
package com.cloudlionheart.museumsearchapplication;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
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.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class DisplaySearchResultsActivity extends ListActivity
{
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> museumItemsList;
// url to get all products list
private static String url_search_results = "http://10.0.3.2/android_connect/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_MUSEUM_ITEMS = "museumItems";
private static final String TAG_MUSEUM_ITEM_ID = "id";
private static final String TAG_MUSEUM_ITEM_NAME = "itemName";
private static final String TAG_MUSEUM_ITEM_ARTIST = "artistName";
private static final String TAG_MUSEUM_ITEM_LOCATION = "itemLocation";
private static final String TAG_MUSEUM_ITEM_HISTORICAL_PERIOD = "itemHistoricalPeriod";
private static final String TAG_MUSEUM_ITEM_IMAGE = "itemImage";
// products JSONArray
JSONArray museumItems = null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_search_resaults);
// Hashmap for ListView
museumItemsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
}
/**
* Background Async Task to Load all product by making HTTP Request
*/
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(DisplaySearchResultsActivity.this);
pDialog.setMessage("Loading Museum Items. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
*/
protected String doInBackground(String... args)
{
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_search_results, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Museum Items: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
museumItems = json.getJSONArray(TAG_MUSEUM_ITEMS);
// looping through All Products
for (int i = 0; i < museumItems.length(); i++)
{
JSONObject c = museumItems.getJSONObject(i);
// Storing each json item in variable
String item_id = c.getString(TAG_MUSEUM_ITEM_ID);
String item_name = c.getString(TAG_MUSEUM_ITEM_NAME);
String item_artist = c.getString(TAG_MUSEUM_ITEM_ARTIST);
String item_historic_period = c.getString(TAG_MUSEUM_ITEM_HISTORICAL_PERIOD);
String item_location = c.getString(TAG_MUSEUM_ITEM_LOCATION);
String list_image = c.getString(TAG_MUSEUM_ITEM_IMAGE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_MUSEUM_ITEM_ID, item_id);
map.put(TAG_MUSEUM_ITEM_NAME, item_name);
map.put(TAG_MUSEUM_ITEM_ARTIST, item_artist);
map.put(TAG_MUSEUM_ITEM_HISTORICAL_PERIOD, item_historic_period);
map.put(TAG_MUSEUM_ITEM_LOCATION, item_location);
map.put(TAG_MUSEUM_ITEM_IMAGE, list_image);
// adding HashList to ArrayList
museumItemsList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* *
*/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
DisplaySearchResultsActivity.this, museumItemsList,
R.layout.list_item, new String[]{TAG_MUSEUM_ITEM_ID,
TAG_MUSEUM_ITEM_NAME, TAG_MUSEUM_ITEM_ARTIST,
TAG_MUSEUM_ITEM_HISTORICAL_PERIOD, TAG_MUSEUM_ITEM_LOCATION,
TAG_MUSEUM_ITEM_IMAGE},
new int[]{R.id.museum_item_id, R.id.museum_item_name,
R.id.museum_item_artist, R.id.museum_item_historic_period,
R.id.museum_item_location, R.id.museum_list_image});
// updating listview
setListAdapter(adapter);
}
});
}
}
}
and my other class
JSONParser.java
package com.cloudlionheart.museumsearchapplication;
/**
* Created by CloudLionHeart on 5/7/2015.
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.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 jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
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;
}
}
Using Picasso:
Picasso.with(context)
.load(imageUrl)
.into(imageView);
You can use image loader library to load image dynamically into imageview.
As it given easy documentation, just follow it. You have to pass url of image.
I Hope it will help you..!
public class LoadImageFromURL extends AsyncTask{
#Override
protected Bitmap doInBackground(String... params) {
try {
URL url = new URL("image-url");
InputStream is = url.openConnection().getInputStream();
Bitmap bitMap = BitmapFactory.decodeStream(is);
return bitMap;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
yourImageview.setImageBitmap(result);
}
}
<uses-permission android:name="android.permission.INTERNET"/>
add Permission into you manifest.
Related
i am just a beginner in developing android applications, i wanted to connect my application to a server so i could get data from MySQL. so i tried to make login part first but i have some problems. my code doesn't work for reading JSON.
my codes are as below:
LoginActivity(MainActivity) :
package ir.naserpour.sportclub;
import android.content.Context;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;
public class LoginActivity extends AppCompatActivity {
String link;
String response;
//get values
String username,password;
#Override
protected void attachBaseContext (Context newBase){
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//define things
TextView menu = (TextView) findViewById(R.id.menu);
final EditText login_username = (EditText) findViewById(R.id.login_username);
final EditText login_password = (EditText) findViewById(R.id.login_password);
Button login_login = (Button) findViewById(R.id.login_login);
Button login_register = (Button)findViewById(R.id.login_register);
CheckBox rememberme = (CheckBox)findViewById(R.id.login_remeberme);
//set icon type face
Typeface fonticon = Typeface.createFromAsset(getAssets(), "fonts/icon.ttf");
menu.setTypeface(fonticon);
login_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
username = login_username.getText().toString();
password = login_password.getText().toString();
//check values
if (username.length() <1 || password.length() < 1) {
Toast.makeText(getApplicationContext(), "fields cannot be empty", Toast.LENGTH_SHORT).show();
} else {
//generate link
link = "http://localhost:8080/login.php?username="+username+"&password="+password;
login();
if(response=="true"){
Toast.makeText(getApplicationContext(), "true", Toast.LENGTH_SHORT).show();
}else if(response=="false"){
Toast.makeText(getApplicationContext(), "false", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "response", Toast.LENGTH_SHORT).show();
}
}
}
});
}
#Override
protected void onPause () {
super.onPause();
finish();
}
public String login() {
new JSONParse().execute();
return response;
}
public class JSONParse extends AsyncTask<String, String, JSONObject> {
#Override
public void onPreExecute() {
super.onPreExecute();
Toast.makeText(getApplicationContext(),"getting data ...",Toast.LENGTH_SHORT).show();
}
#Override
public JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(link);
return json;
}
#Override
public void onPostExecute(JSONObject json) {
try {
JSONArray result = json.getJSONArray("result");
JSONObject c = result.getJSONObject(0);
try {
String res = new String(c.getString("response").getBytes("ISO-8859-1"), "UTF-8");
response = res;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
JSONParser.java:
package ir.naserpour.sportclub;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
/**
* Created by Mohammad Naserpour on 9/22/2016.
*/
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httppost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
and also my login.php script:
<?php
define("HOST","localhost");
define("USERNAME","root");
define("PASSWORD","");
define("NAME","users");
$con = mysqli_connect(HOST,USERNAME,PASSWORD,NAME);
$username = $_GET["username"];
$password = $_GET["password"];
$sql = "SELECT * FROM userinfo WHERE username ='$username' AND password='$password'";
$check = mysqli_fetch_array(mysqli_query($con,$sql));
if(isset($check)){
echo '{"result":[{"response":"true"}]}';
}else{
echo '{"result":[{"response":"false"}]}';
}
mysqli_close($con);
?>
i would be so happy if i find out the problem. thank you.
see this tutorial :
its a full tutorial about login process using google volley
First : On device side, Use volley, its simple and easy to use
Second : On server, what is {"result":[{"response":"true"}]}
any problem with {"result":true} ??
Last but not the least : Did you use JSON before or this code is trial and error copy paste from some tutorials?
I am trying to develop a simple client-server application in Android. I have a problem while fetching a response from PHP code. It returns an HTML code instead of JSON. Is it a problem with the WAMP server I have used?
Here is the PHP code:
<?php
include_once './connect_db.php';
$db = new DBConnect();
$response = array();
$username = $_POST["username"];
$password = $_POST["password"];
if (empty($_POST['username']) || empty($_POST['password']))
{
$response["success"] = 0;
$response["message"] = "One or both of the fields are empty.";
die(json_encode($response));
}
$query = " SELECT * FROM account 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));
}
mysql_close();
?>
login.java:
package com.example.rossh.register;
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.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
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 AppCompatActivity implements OnClickListener {
private EditText user, pass;
private Button login;
JSONObject jsonObject;
String response;
// Progress Dialog
private ProgressDialog pDialog;
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//setup input fields
user = (EditText) findViewById(R.id.username);
pass = (EditText) findViewById(R.id.password);
//setup buttons
login = (Button) findViewById(R.id.btnlogin);
//register listeners
login.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btnlogin:
String username = user.getText().toString();
String password = pass.getText().toString();
boolean cancel =false;
View focusView = null;
if(TextUtils.isEmpty(username))
{
user.setError("This field is required!!");
cancel=true;
focusView=user;
}
if(TextUtils.isEmpty(password))
{
pass.setError("This field is requird!!!");
cancel=true;
focusView=pass;
}
if(cancel)
{
focusView.requestFocus();
} else {
new AttemptLogin().execute(username, password);
}
break;
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 login...");
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
String username = args[0];
String password = args[1];
// Building Parameters
final int success;
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
// getting product details by making HTTP request
JsonParser jsonParser = new JsonParser();
jsonObject = jsonParser.makeHttpRequest(AppConfig.LOGIN_URL, "POST", params);
if (jsonObject != null) {
try{
Log.d("Json data",">"+jsonObject);
success = jsonObject.getInt(TAG_SUCCESS);
if (success == 1) {
response = jsonObject.getString(TAG_MESSAGE);
} else {
Log.d("Login Failure!", jsonObject.getString(TAG_MESSAGE));
response = jsonObject.getString(TAG_MESSAGE);
}
} catch(JSONException e) {
e.printStackTrace();
}
}
return response;
}
/**
* After completing background task Dismiss the progress dialog
**/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null) {
Toast.makeText(login.this, "ok", Toast.LENGTH_LONG).show();
}
}
}
}
}
jsonParser.java:
package com.example.rossh.register;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.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.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import android.widget.Toast;
public class JsonParser {
InputStream is = null;
static String json = "";
static JSONObject jObj = null;
// constructor
public JsonParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
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));
httpPost.setHeader("Content-Type","application/json");
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, HTTP.UTF_8), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.d("String",">"+json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
JSONArray jsonarray = new JSONArray(json);
jObj = jsonarray.getJSONObject(0);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing " + e.toString());
}
// return JSON String
return jObj;
}
}
It may be due to one or more errors in your HTML, or if your page returns non-text objects. Make sure your HTML webpage does not throw an error while running from browser.
For one thing I would suggest that your PHP script sets proper content type when returning json, see Returning JSON from a PHP Script. Also see Java HttpRequest JSON & Response Handling for how to do JSON requests in java.
Try changing die(json_encode($response)) to echo json_encode($response)
I am trying to send an invoke a webservice method that took a jagged array as a parameters. I build the array, but it always passed null to the web service.
Here is my java class:
package com.mitch.wcfwebserviceexample;
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.client.ClientProtocolException;
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.JSONArray;
import org.json.JSONObject;
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.TextView;
import android.app.Activity;
public class MainActivity extends Activity implements OnClickListener {
private String values ="";
Button btn;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button)this.findViewById(R.id.btnAccess);
tv = (TextView)this.findViewById(R.id.tvAccess);
btn.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
try
{
AsyncTaskExample task = new AsyncTaskExample(this);
task.execute("");
String test = values;
tv.setText(values);
} catch(Exception e)
{
Log.e("Click Exception ", e.getMessage());
}
}
public class AsyncTaskExample extends AsyncTask<String, Void,String>
{
private String Result="";
//private final static String SERVICE_URI = "http://10.0.2.2:1736";
private final static String SERVICE_URI = "http://10.0.2.2:65031/SampleService.svc";
private MainActivity host;
public AsyncTaskExample(MainActivity host)
{
this.host = host;
}
public String GetSEssion(String URL)
{
boolean isValid = true;
if(isValid)
{
String[][] val = {
new String[] {"Student.ID","123456"},
new String[] {"Student.username","user1"},
new String[] {"Student.password","123456"},
new String[] {"Student.location.id","12"}
};
HttpPost requestAuth = new HttpPost(URL +"/Login");
try
{
JSONObject json = new JSONObject();
// json.put("sessionId", sessionId);
JSONArray params = new JSONArray();
params.put(val);
json.put("authenParams", params);
StringEntity se = new StringEntity(json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
requestAuth.setHeader("Accept","application/json");
requestAuth.setEntity(se);
DefaultHttpClient httpClientAuth = new DefaultHttpClient();
HttpResponse responseAuth = httpClientAuth.execute(requestAuth);
HttpEntity responseEntityAuth = responseAuth.getEntity();
char[] bufferAuth = new char[(int)responseEntityAuth.getContentLength()];
InputStream streamAuth = responseEntityAuth.getContent();
InputStreamReader readerAuth = new InputStreamReader(streamAuth);
readerAuth.read(bufferAuth);
streamAuth.close();
String rawAuthResult = new String(bufferAuth);
Result = rawAuthResult;
String d = null;
// }
} catch (ClientProtocolException e) {
Log.e("Client Protocol", e.getMessage());
} catch (IOException e) {
Log.e("Client Protocol", e.getMessage() );
} catch(Exception e)
{
Log.e("Client Protocol", e.getMessage() );
}
}
return Result;
}
#Override
protected String doInBackground(String... arg0) {
android.os.Debug.waitForDebugger();
String t = GetSEssion(SERVICE_URI);
return t;
}
#Override
protected void onPostExecute(String result) {
// host.values = Result;
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected void onCancelled() {
// TODO Auto-generated method stub
super.onCancelled();
}
}
}
Below is my method that is supposed to recieve the parameter:
I put a break point in the code below and check it. The parameter is always null.
public string Login(string[][] value)
{
string[] tester = null;
string testerExample="";
foreach (string[] st in value)
{
tester = st;
}
foreach (string dt in tester)
{
testerExample = dt;
}
return testerExample;
}
Here is the method declaration in IStudentService:
[OperationContract]
[WebInvoke(
Method="POST", UriTemplate="Login", BodyStyle= WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
string Login(string[][] value);
I tried to as you suggested, and it did not work. It return "Request Error"
Here is the sample code that I paste.
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://10.0.2.2:65031/SampleService.svc/login");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("tester","abcd"));
pairs.add(new BasicNameValuePair("sampletest","1234"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs,HTTP.UTF_8);
post.setEntity(entity);
HttpResponse response = client.execute(post);
HttpEntity responseEntity = response.getEntity();
char[] buffer = new char[(int)responseEntity.getContentLength()];
InputStream stream = responseEntity.getContent();
InputStreamReader reader = new InputStreamReader(stream);
reader.read(buffer); stream.close();
String value = new String(buffer);
I finally got it to work they way that I want it to. The issue was that I was building the Array this way (see below section 1) and pass it to the JSONObject or JSONArray. I switched and build the Array using JSONArray and pass it to the JSONObject (see section 2). It works like a charm.
Section1:
Wrong way to do it - (It may work this way if you were to look through the array and put them in a JSONArray. It's will be too much work when it can be done directly.)
String[][] Array = {
new String[]{"Example", "Test"},
new String[]{"Example", "Test"},
};
JSONArray jar1 = new JSONArray();
jar1.put(0, Array); **// Did not work**
Section 2:
The way I did it after long hours of trying and some very helpful tips and hints from #vorrtex.
JSONArray jar1 = new JSONArray();
jar1.put(0, "ABC");
jar1.put(1, "Son");
jar1.put(2, "Niece");
JSONArray jarr = new JSONArray();
jarr.put(0, jar1);
JSONArray j = new JSONArray();
j.put(0,"session");
JSONObject obj = new JSONObject();
obj.put("value", jarr);
obj.put("test", j);
obj.put("name","myName");
Log.d("Obj.ToString message: ",obj.toString());
StringEntity entity = new StringEntity(obj.toString());
Looking at the web service, and it has exactly what I was looking for.
Thanks for you help!!!!
i'm try to convert json array from internet to listview. the php code in server work correctly and return the json string below.
the result json in logcat is :
11-09 20:47:04.170: I/AllNotes >> jSon >>(429): {"notes":{"3":{"note_subject":"dshjdsfjsdfsdhf","note_id":"4","note_date":"0000-00-00"},"2":{"note_subject":"dshjdsfjsdfsdhf","note_id":"3","note_date":"0000-00-00"},"1":{"note_subject":"dshjdsfjsdfsdhf","note_id":"2","note_date":"0000-00-00"},"0":{"note_subject":"dshjdsfjsdfsdhf","note_id":"1","note_date":"0000-00-00"},"7":{"note_subject":"dshjdsfjsdfsdhf","note_id":"8","note_date":"1391\/8\/19"},"6":{"note_subject":"dshjdsfjsdfsdhf","note_id":"7","note_date":""},"5":{"note_subject":"dshjdsfjsdfsdhf","note_id":"6","note_date":""},"4":{"note_subject":"dshjdsfjsdfsdhf","note_id":"5","note_date":""}},
"success":"1"}
my JSONParser class is :
package ir.mohammadi.android.nightly;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = null;
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
// Make HTTP connection
try {
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();
Log.i("Input stream >> ", is.toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.i("JSON string builder >> ", json.toString());
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try {
jObj = new JSONObject(json.substring(1, json.length()));
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;
}
}
error is : at notes of type org.json.JSONObject cannot be converted to JSONArray
the code that show json in list view is :
package ir.mohammadi.android.nightly;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class AllNotes extends ListActivity {
ProgressDialog pDialog;
ArrayList<HashMap<String, String>> noteList;
JSONArray notes = null;
JSONObject jSon = null;
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR_MSG = "error_message";
private static String KEY_NOTE_ID = "note_id";
private static String KEY_NOTE_SUBJECT = "note_subject";
private static String KEY_NOTE_DATE = "note_date";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.note_list);
noteList = new ArrayList<HashMap<String, String>>();
new LoadAllNotes().execute();
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String note_id = ((TextView) view
.findViewById(R.id.list_lbl_id)).getText().toString();
Intent i = new Intent(getApplicationContext(), NoteDetail.class);
i.putExtra("note_id", note_id);
startActivityForResult(i, 100);
}
});
}
public class LoadAllNotes extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllNotes.this);
pDialog.setMessage("لطفا صبر کنید...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
UserFunctions userFunctions = new UserFunctions();
jSon = userFunctions.getAllNotes("12");
Log.i("AllNotes >> jSon >>", jSon.toString());
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
try {
if (jSon.has(KEY_SUCCESS)) {
String success = jSon.getString(KEY_SUCCESS);
if (success.equals("1")) {
notes = jSon.getJSONArray("notes");
for (int i = 0; i < notes.length(); i++) {
JSONObject c = notes.getJSONObject(i);
String id = c.getString(KEY_NOTE_ID);
String subject = c.getString(KEY_NOTE_SUBJECT);
String date = c.getString(KEY_NOTE_DATE);
HashMap<String, String> map = new HashMap<String, String>();
map.put(KEY_NOTE_ID, id);
map.put(KEY_NOTE_SUBJECT, subject);
map.put(KEY_NOTE_DATE, date);
noteList.add(map);
}
}
} else {
finish();
Toast.makeText(getApplicationContext(),
jSon.getString(KEY_ERROR_MSG), Toast.LENGTH_SHORT)
.show();
Log.i("AllNotes >> No nightly >>", "...");
Intent i = new Intent(getApplicationContext(), login.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(AllNotes.this,
noteList, R.layout.list_item, new String[] {
KEY_NOTE_ID, KEY_NOTE_SUBJECT,
KEY_NOTE_DATE }, new int[] {
R.id.list_lbl_id, R.id.list_lbl_subject,
R.id.list_lbl_date });
setListAdapter(adapter);
}
});
}
}
}
and the php code is :
public function getNotesList($user_id)
{
$result = mysql_query("SELECT `id`, `note_subject`, `note_date` FROM `tbl_notes` WHERE `user_id` = '$user_id'");
if (mysql_num_rows($result) > 0) {
$response = array();
$response["success"] = "1";
$response["notes"] = array();
while ($row = mysql_fetch_array($result)) {
$note = array();
$note["note_id"] = $row["id"];
$note["note_subject"] = $row["note_subject"];
$note["note_date"] = $row["note_date"];
array_push($response["notes"], $note);
}
return $response;
}
}
and
if ($tag == 'getNotesList') {
$user_id = $_POST['user_id'];
$result = $db->getNotesList($user_id);
if ($result) {
error_log("Index getNotesList Json >>" . json_encode($result) . "\r\n", 3,
"Log.log");
echo json_encode($result, JSON_FORCE_OBJECT);
} else {
$response["error"] = "1";
$response["error_message"] = "no row";
echo json_encode($response, JSON_FORCE_OBJECT);
}
}
how can i fix this? thanks.
use
JSONObject notes = jSon.getJSONObject("notes");
instead of
JSONArray notes = jSon.getJSONArray("notes");`
Because your json String is collection of JsonOject's it's not contains any JsonArray.
you can use following json checker site before parsing it to known the structure of Json String
http://jsonviewer.stack.hu/
I am try to retrive(read) an array of course form database (mysql) and display it as list of item in my android activity the problem is i have more than one row in my table (course) but it retrive only the first row also if the table (course) have know data insert my application step after the run even that i have case in my code that display toast message that say there is no course
class JSONParser.java
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;
}
}
class ViewALLCourseStudent.java
package com.ksu.sms;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
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.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class ViewALLCourseStudent extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser(); //class
ArrayList<HashMap<String, String>> coursesList;
//url to get all products list
private static String url_all_course = "http://10.0.2.2/SmsPhp/view_all_course.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_course = "course";
private static final String TAG_CourseID = "CourseID";
private static final String TAG_Name = "Name";
// course JSONArray
JSONArray courses = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_all_course_student);
coursesList = new ArrayList<HashMap<String, String>>();
// Loading courses in Background Thread
new LoadAllCourses().execute();
// Get list view
ListView lv = getListView();
// on seleting single course
// launching Edit course Screen
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) //one of the list
{
// getting values from selected ListItem
String CourseID = ((TextView) view.findViewById(R.id.CourseID)).getText()
.toString();
// Starting new intent
Intent ViewCourseStudent = new Intent(getApplicationContext(),
ViewCourseStudent.class);
// sending Course ID to next activity
ViewCourseStudent.putExtra(TAG_CourseID, CourseID);
// starting new activity and expecting some response back
startActivityForResult(ViewCourseStudent, 100);
}
});
}
// Response from view course Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user view course
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all course by making HTTP Request
* */
class LoadAllCourses extends AsyncTask<String, String, String>
{
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ViewALLCourseStudent.this);
pDialog.setMessage("Loading Courses. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from u r l
* */
#Override
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_course, "GET", params);
// Check your log cat for JSON response
Log.d("All courses: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// course found
// Getting Array of course
courses = json.getJSONArray(TAG_course);
// looping through All courses
for (int i = 0; i < courses.length(); i++)//course JSONArray
{
JSONObject c = courses.getJSONObject(i); // read first
// Storing each json item in variable
String CourseID = c.getString(TAG_CourseID);
String Name = c.getString(TAG_Name);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_CourseID, CourseID);
map.put(TAG_Name, Name);
// adding HashList to ArrayList
coursesList.add(map);
}
} else {
Toast.makeText(getBaseContext(),"there is no course" ,Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
ViewALLCourseStudent.this, coursesList,
R.layout.list_item, new String[] { TAG_CourseID,
TAG_Name},
new int[] { R.id.CourseID, R.id.Name });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
and php for view all course
<?php
/*
* Following code will list all the course
*/
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// get all courses from course table
$result = mysql_query("SELECT *FROM course") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0)
{
// looping through all results
// products node
$response["course"] = array();
while ($row = mysql_fetch_array($result))
{
// temp user array
$course = array();
$course["CourseID"] = $row["CourseID"];
$course["Code"] = $row["Code"];
$course["Name"] = $row["Name"];
$course["OfficeHours"] = $row["OfficeHours"];
$course["CreditHours"] = $row["CreditHours"];
$course["Description"] =$row["Description"];
$course["MaxAbsenceDays"]= $row["MaxAbsenceDays"];
$course["ExamsDates"] = $row["ExamsDates"];
// push single product into final response array
array_push($response["course"], $course);
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
}
}
else {
// no products found
$response["success"] = 0;
$response["message"] = "No products found";
// echo no users JSON
echo json_encode($response);
}
?>
Any thing you want i can explain.
Look at the example given in halloandrdoid or SPTechnolab blog
There is a good example for connecting MySql using PHP and it worked for me.