Android Get data from server to android issue - java

I want to get data from server and save it in the listview I have write right code there is no error but when I click on activity app stopped here is my activity code/
public class UserListActivity extends ActionBarActivity {
String myJSON;
private static final String TAG_RESULTS="result";
// private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL ="email";
JSONArray peoples = null;
ArrayList<HashMap<String, String>> personList;
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_list);
list = (ListView) findViewById(R.id.listView);
personList = new ArrayList<HashMap<String,String>>();
getData();
}
protected void showList(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
peoples = jsonObj.getJSONArray(TAG_RESULTS);
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
//String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
HashMap<String,String> users = new HashMap<String,String>();
// persons.put(TAG_ID,id);
users.put(TAG_NAME,name);
users.put(TAG_EMAIL,email);
personList.add(users);
}
ListAdapter adapter = new SimpleAdapter(
UserListActivity.this, personList, R.layout.list_item,
new String[]{TAG_NAME,TAG_EMAIL},
new int[]{R.id.name, R.id.email}
);
list.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://samplechatapp.gear.host/Get-Data.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON=result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
}
This is log cat message:
This is the data on the server which I want to get.

Related

Json parsing errors at android

I want to parse below data but I got a errors when I try other url like this http://api.learn2crack.com/android/jsonos/ for the parsing json data I can parsing data,but when I try below code for the parsing I got a below error.
Activity jsonparse.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41b86fb8 V.E..... R......D 0,0-580,162} that was originally added here
android.view.WindowLeaked: Activity jsonparse.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41b86fb8 V.E..... R......D 0,0-580,162} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:409)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:218)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:281)
at jsonparse.MainActivity$DownloadJSON.onPreExecute(MainActivity.java:58)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at jsonparse.MainActivity.onCreate(MainActivity.java:38)
at android.app.Activity.performCreate(Activity.java:5122)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2307)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)
at android.app.ActivityThread.access$600(ActivityThread.java:162)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5371)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
)
{
"AllUsersResult":[
{
"GroupID":null,
"ID":1,
"Password":"1234",
"Role":null,
"Username":"admin",
"customerID":null
}
]
}
MainActivity class
public class MainActivity extends Activity {
ListView list;
TextView ver;
TextView name;
TextView api;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "http://192.168.0.39:8090/TrackBinSvc.svc/AllUsers/admin/1234";
//JSON Node Names
private static final String TAG_OS = "AllUsersResult";
private static final String TAG_VER = "GroupID";
private static final String TAG_NAME = "Password";
private static final String TAG_API = "Username";
JSONArray android = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oslist = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
ver = (TextView)findViewById(R.id.vers);
name = (TextView)findViewById(R.id.name);
api = (TextView)findViewById(R.id.api);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
android = json.getJSONArray(TAG_OS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String ver = c.getString(TAG_VER);
String name = c.getString(TAG_NAME);
String api = c.getString(TAG_API);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_VER, ver);
map.put(TAG_NAME, name);
map.put(TAG_API, api);
oslist.add(map);
list = (ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_v,
new String[] { TAG_VER,TAG_NAME, TAG_API }, new int[] {
R.id.vers,R.id.name, R.id.api});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
JSONParser class
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;
}
}
I am suggest you parse data with volley library it is easy to use and also flexible ! Here is Tutorial link !
Hope this will helps you ! Cheers !
Change your JSONParse class to this..
private class JSONParse extends AsyncTask<String, String, ArrayList<HashMap<String, String>>> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
ver = (TextView)findViewById(R.id.vers);
name = (TextView)findViewById(R.id.name);
api = (TextView)findViewById(R.id.api);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected ArrayList<HashMap<String, String>> doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
if(json!=null)
{
// Getting JSON Array from URL
android = json.getJSONArray(TAG_OS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String ver = c.getString(TAG_VER);
String name = c.getString(TAG_NAME);
String api = c.getString(TAG_API);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_VER, ver);
map.put(TAG_NAME, name);
map.put(TAG_API, api);
oslist.add(map);
return oslist;
}
//else DATA Not Found or Server not connected
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result_list) {
if(pDialog!=null)
{
pDialog.dismiss();
}
list = (ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, result_list,
R.layout.list_v,
new String[] { TAG_VER,TAG_NAME, TAG_API }, new int[] {
R.id.vers,R.id.name, R.id.api});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+result_list.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
}
}
Hope this will help you.

How i can know if the conection to server is correct or not?

I make a login but i need know when the conection to server is fail
,this is my event of button
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
usuario=(EditText)findViewById(R.id.etUsuario);
contrasena=(EditText)findViewById(R.id.etContrasena);
usuario_ws = usuario.getText().toString();
pass_ws = contrasena.getText().toString();
new HttpAsyncTask().execute(GET());
}
});
and this is my asynctask for the response of my server
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
return GET();
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
// Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show();
// etResponse.setText(result);
Integer respuesta_ws = Integer.valueOf(result);
if (respuesta_ws>=1){
sesionIn();
}
else if (respuesta_ws==0){
sesionFail();
}
}
}
public String GET() {
String url = "http://"+ippref+":8080/WSAppInventario/webresources/inventario.users/Login/"+usuario_ws+"/"+pass_ws+"";
String result = "";
BufferedReader inStream = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpRequest = new HttpGet(url);
HttpResponse response = httpClient.execute(httpRequest);
inStream = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent()));
StringBuffer buffer = new StringBuffer();
String line = "";
//String NL = System.getProperty("line.separator");
while ((line = inStream.readLine()) != null) {
buffer.append(line);
}
inStream.close();
result = buffer.toString();
respuesta_ws = Integer.valueOf(result);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
The string ippref
It is an object to keep before SharedPreferences
this should work
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
return GET();
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
// Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show();
// etResponse.setText(result);
if (result=="failed"){
sesionFail();
}
else{
sesionIn();
}
}
}
public String GET() {
String url = "http://"+ippref+":8080/WSAppInventario/webresources/inventario.users/Login/"+usuario_ws+"/"+pass_ws+"";
String result = "";
BufferedReader inStream = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpRequest = new HttpGet(url);
HttpResponse response = httpClient.execute(httpRequest);
inStream = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent()));
StringBuffer buffer = new StringBuffer();
String line = "";
//String NL = System.getProperty("line.separator");
while ((line = inStream.readLine()) != null) {
buffer.append(line);
}
inStream.close();
result = buffer.toString();
respuesta_ws = Integer.valueOf(result);
} catch (Exception e) {
e.printStackTrace();
return "failed";
}
return result;
}

Populating listview from database (localhost phpmyadmin)

I tried searching for similar questions but I cant find anything that fits in to what I am doing.. I'm trying to populate a listview from a database and whenever I run it, it doesn't display anything in the listview..
here is the logcat..
JSONException: Value {"message":"Patient Available","success":1,"post":[{"lname":"miradora doringo","address":"navotas, pilipinas","email":"tam.muqu23","age":"20","gender":"babae","remarks":"mabuting estudyante","patient_id":"6","contact":"361008762","fname":"jenelien"},{"lname":"andres","address":"manila","email":"julieannandres#gmail.com","age":"20","gender":"female","remarks":"trial","patient_id":"7","contact":"926644895","fname":"julie"}]} of type org.json.JSONObject cannot be converted to JSONArray
this is my Viewpatient.java:
public class Viewpatient extends ListActivity {
private Button create;
private ProgressDialog pDialog;
private static final String READ_PATIENT_URL = "http://192.168.43.15:8080/DoctorScheduler/activities/viewpatient.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private static final String TAG_POST = "post";
private static final String TAG_PATIENT = "patient_id";
private static final String TAG_FNAME = "fname";
private static final String TAG_LNAME = "lname";
private static final String TAG_AGE = "age";
private static final String TAG_GENDER = "gender";
private static final String TAG_CONTACT = "contact";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_REMARKS = "remarks";
JSONParser jsonParser = new JSONParser();
//array of all patient information by patient
JSONArray Apatient = null;
//manages all patient in a list
ArrayList<HashMap<String, String>> ApatientList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_viewpatient);
ApatientList = new ArrayList<HashMap<String, String>>();
new LoadInformation().execute();
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
// INSERT ALL PREVIOUS CONSULTATIONS OF THE PATIENT HERE
}
});
create = (Button) findViewById(R.id.BtnAdd);
create.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent createInfo = new Intent(Viewpatient.this, Viewupdate.class);
startActivity(createInfo);
}
});
};
public class LoadInformation extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(Viewpatient.this);
pDialog.setMessage("Loading all patient information....");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
}
#Override
protected Void doInBackground(Void... args) {
// TODO Auto-generated method stub
List<NameValuePair> params = new ArrayList<NameValuePair>();
// Making a request to url and getting response
String json = jsonParser.getJSONFromURL(READ_PATIENT_URL, "POST", params);
Log.d("Response: ", "> " + json);
try {
Apatient = new JSONArray(json);
if (Apatient != null) {
// looping
for (int i = 0; i < Apatient.length(); i++) {
JSONObject c = Apatient.getJSONObject(i);
String patient_id = c.getString(TAG_PATIENT);
String fname = c.getString(TAG_FNAME);
String lname = c.getString(TAG_LNAME);
String age = c.getString(TAG_AGE);
String gender = c.getString(TAG_GENDER);
String contact = c.getString(TAG_CONTACT);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String remarks = c.getString(TAG_REMARKS);
// tmp hashmap for single contact
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PATIENT, patient_id);
map.put(TAG_FNAME, fname);
map.put(TAG_LNAME, lname);
map.put(TAG_AGE, age);
map.put(TAG_GENDER, gender);
map.put(TAG_CONTACT, contact);
map.put(TAG_EMAIL, email);
map.put(TAG_ADDRESS, address);
map.put(TAG_REMARKS, remarks);
// adding contact to contact list
ApatientList.add(map);
}
} else {
Log.e("Error", "Couldn't get any data from the url");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
//super.onPostExecute(result);
pDialog.dismiss();
runOnUiThread(new Runnable(){
public void run(){
ListAdapter adapter = new SimpleAdapter(
Viewpatient.this, ApatientList, R.layout.main,
new String[] { TAG_PATIENT, TAG_FNAME, TAG_LNAME, TAG_AGE,
TAG_GENDER, TAG_CONTACT, TAG_EMAIL, TAG_ADDRESS, TAG_REMARKS },
new int[] { R.id.txtID, R.id.txtFName, R.id.txtLName, R.id.txtAge, R.id.txtGender,
R.id.txtContact, R.id.txtEmail, R.id.txtAddress, R.id.txtRemarks});
setListAdapter(adapter);
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.viewpatient, menu);
return true;
}
}
this my JSONParser.java:
public class JSONParser {
//new
static String response = null;
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
//constructor
public JSONParser(){
}
public String getJSONFromURL(String url, String 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;
}
}
and this is my viewpatient.php:
<?php
require ("../config.inc.php");
$query = "Select * From patientinfo";
try{
$stmt = $dbname->prepare($query);
$result = $stmt->execute();
}catch(PDOException $ex){
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
//retrieve all the rows
$rows = $stmt->fetchAll();
if($rows){
$response["success"] = 1;
$response["message"] = "Patient Available";
$response["post"] = array();
foreach($rows as $row){
$post = array();
$post["patient_id"] = $row["patient_id"];
$post["fname"] = $row["fname"];
$post["lname"] = $row["lname"];
$post["age"] = $row["age"];
$post["gender"] = $row["gender"];
$post["contact"] = $row["contact"];
$post["email"] = $row["email"];
$post["address"] = $row["address"];
$post["remarks"] = $row["remarks"];
//update json response
array_push($response["post"], $post);
}
echo json_encode($response);
}
else{
$response["success"] = 0;
$response["message"] = "No available patient information";
die(json_encode($response));
}
?>
You should change this part Apatient = new JSONArray(json);
Create a JSONObject JSONObject ApatientObject = new JSONObject(json);
Then get your JSONArray from there like this :
Apatient = new JSONArray(ApatientObject.getJSONArray("post"))
The problem is that the response you receive from the server is a JSONObject, not a JSONArray. The JSONObject contains 2 Strings, "message" and "success", and also contains a JSONArray "post" which holds the data you are looking for.
EDIT:
If you're only retreiving data from the server then it can be useful to think in terms of using GET for retrieving / viewing information and POST for creating / editing information as mentioned here:
When do you use POST and when do you use GET?

How to Parse URL with JSON object -Android [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
i have the URL (.com) which has the JSON object .. i created the JSON object using PHP and uploaded in a server so it will be dynamically updated (similar to RSS). I face two problems the first one shows error " and of type java.Lang.String cannot be converted to JSON object" so i used this code and the error goes:
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;
}
}
The SingleMenuItemActivity calss:
public class SingleMenuItemActivity extends Activity {
// JSON node keys
private static final String TAG_Title = "Title";
private static final String TAG_Date = "Date";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_list_item);
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
String name = in.getStringExtra(TAG_Title);
String description = in.getStringExtra(TAG_Date);
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblCost = (TextView) findViewById(R.id.email_label);
lblName.setText(name);
lblCost.setText(description);
}
}
The AndroidJasonParsingActivity calss:
public class AndroidJSONParsingActivity extends ListActivity {
// url to make request
private static String url = "http://www.rssparser.host22.com/";
// JSON Node names
private static final String TAG_NAME = "Title";
private static final String TAG_Image = "Image";
private static final String TAG_Category = "Category";
private static final String TAG_Venue = "Venue";
private static final String TAG_Date = "Date";
// contacts JSONArray
JSONArray contacts = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
//contacts = json.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String name = c.getString(TAG_NAME);
String Image = c.getString(TAG_Image);
String Category = c.getString(TAG_Category);
String Venue = c.getString(TAG_Venue);
String Date = c.getString(TAG_Date);
// Phone number is agin JSON Object
JSONObject phone = c.getJSONObject(TAG_Date);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_NAME, name);
map.put(TAG_Image, Image);
map.put(TAG_Date , Date );
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.list_item,
new String[] { TAG_NAME, TAG_Date }, new int[] {
R.id.name, R.id.email, R.id.mobile });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.email)).getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_Date, description);
startActivity(in);
}
});
}
}
first create JSONParser.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
then create activity
public class AndroidJSONParsingActivity extends ListActivity {
// url to make request
private static String url = "http://api.androidhive.info/contacts/";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray contacts = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = json.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone number is agin JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_EMAIL, email);
map.put(TAG_PHONE_MOBILE, mobile);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.list_item,
new String[] { TAG_NAME, TAG_EMAIL, TAG_PHONE_MOBILE }, new int[] {
R.id.name, R.id.email, R.id.mobile });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.email)).getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_PHONE_MOBILE, description);
startActivity(in);
}
});
}
}
and write Internet permission in manifest file
this is best tutorial

JSON parsing android

I need advice about my code.
I'm trying to parse a JSON array generated by the PHP function json_encode().
My json:
{"data": [{"streamer":"froggen","yt_length":"25078"},{"streamer":"wingsofdeath","yt_length":"8979"},{"streamer":"guardsmanbob","yt_length":"4790"},{"streamer":"kaostv","yt_length":"4626"},{"streamer":"kungentv","yt_length":"3883"},{"streamer":"destiny","yt_length":"3715"},{"streamer":"zekent","yt_length":"3428"},{"streamer":"athenelive","yt_length":"1673"},{"streamer":"frommaplestreet","yt_length":"1614"},{"streamer":"keyorikeys","yt_length":"1410"},{"streamer":"riotgamesturkish","yt_length":"1397"},{"streamer":"vman7","yt_length":"1022"},{"streamer":"tiensinoakuma","yt_length":"967"},{"streamer":"affenklappe","yt_length":"748"},{"streamer":"teamkeyd","yt_length":"747"},{"streamer":"lagtvmaximusblack","yt_length":"683"},{"streamer":"lolgameru","yt_length":"665"},{"streamer":"gruntartv","yt_length":"585"},{"streamer":"entenzwerg","yt_length":"579"},{"streamer":"lolgameru_cauthonpro","yt_length":"506"},{"streamer":"basickz","yt_length":"488"},{"streamer":"ilysuiteheart","yt_length":"491"},{"streamer":"kireiautumn","yt_length":"485"},{"streamer":"ultimavv","yt_length":"471"}]}
Java class:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
String response = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet(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), 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 activity:
public class AndroidJSONParsingActivity extends ListActivity {
// url to make request
private static String url = "http://ololo.tv/vasa";
// JSON Node names
private static final String TAG_DATA = "data";
private static final String TAG_STREAMER = "streamer";
private static final String TAG_VIEWERS = "yt_length";
// contacts JSONArray
JSONArray data = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Hashmap for ListView
ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser Parser = new JSONParser();
// getting JSON string from URL
JSONObject json = null;
json = Parser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
data = json.getJSONArray(TAG_DATA);
// looping through All Contacts
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
// Storing each json item in variable
String streamer = c.getString(TAG_STREAMER);
String viewers = c.getString(TAG_VIEWERS);
//String link = c.getString();
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_STREAMER, streamer);
map.put(TAG_VIEWERS, viewers);
//map.put(TAG_URL, link);
// adding HashList to ArrayList
dataList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, dataList,
R.layout.list_item,
new String[] { TAG_STREAMER, TAG_VIEWERS /*TAG_URL*/ }, new int[] {
R.id.streamer, R.id.viewers /*R.id.url*/ });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.streamer)).getText().toString();
String viewers_count = ((TextView) view.findViewById(R.id.viewers)).getText().toString();
//String url = ((TextView) view.findViewById(R.id.url)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_STREAMER, name);
in.putExtra(TAG_VIEWERS, viewers_count);
//in.putExtra(TAG_PHONE_MOBILE, url);
startActivity(in);
}
});
}
}
I tried using breakpoints, and see that when I put a breakpoint after GetEntity, the program doesn't get there because it crashed early, or something.
This my async task.
public class ParsingTask extends AsyncTask<String, Void, Void>{
JSONParser Parser = new JSONParser();
protected Void doInBackground(String... urls) {
ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>();
JSONObject json = Parser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
data = json.getJSONArray(TAG_DATA);
// looping through All Contacts
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
// Storing each json item in variable
String streamer = c.getString(TAG_STREAMER);
String viewers = c.getString(TAG_VIEWERS);
//String link = c.getString();
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_STREAMER, streamer);
map.put(TAG_VIEWERS, viewers);
//map.put(TAG_URL, link);
// adding HashList to ArrayList
dataList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, dataList,
R.layout.list_item,
new String[] { TAG_STREAMER, TAG_VIEWERS /*TAG_URL*/ }, new int[] {
R.id.streamer, R.id.viewers /*R.id.url*/ });
setListAdapter(adapter);
return null;
}
protected void onProgressUpdate() {
}
protected void onPostExecute() {
}
}
ListAdapter error, seems like something wrong in "this". This my version how cut off code, where it stop return variables. Sorry for bad english, but i hope you understand me :)
Add my php json maker. Mb problem there?!
<?php
mysql_connect("localhost","root","");
if (!mysql_select_db("ololo")) {
echo "Unable to select ololo: " . mysql_error();
}
$sql=mysql_query("select streamer, yt_length from pm_videos where category='1'");
if(!$sql) exit("Error - ".mysql_error().", ".$tmp_q);
while($row=mysql_fetch_assoc($sql)){
$output[]=$row;
}
$json = json_encode($output);
header('Content-Type: application/json');
print "{\"data\": ${json}}";
mysql_close();
?>
You programm crashes because you are running
json = Parser.getJSONFromUrl(url);
in the UI Thread context. You have to use an AsyncTask
Code looks good. The only problem is that
public class ParsingTask extends AsyncTask<String, Void, ArrayList<HashMap<String, String>>>{
JSONParser Parser = new JSONParser();
protected Void doInBackground(String... urls) {
ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>();
JSONObject json = Parser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
data = json.getJSONArray(TAG_DATA);
// looping through All Contacts
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
// Storing each json item in variable
String streamer = c.getString(TAG_STREAMER);
String viewers = c.getString(TAG_VIEWERS);
//String link = c.getString();
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_STREAMER, streamer);
map.put(TAG_VIEWERS, viewers);
//map.put(TAG_URL, link);
// adding HashList to ArrayList
dataList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
return dataList;
}
protected void onPostExecute(ArrayList<HashMap<String, String>> dataList) {
ListAdapter adapter = new SimpleAdapter(AndroidJSONParsingActivity.this, dataList,
R.layout.list_item,
new String[] { TAG_STREAMER, TAG_VIEWERS /*TAG_URL*/ }, new int[] {
R.id.streamer, R.id.viewers /*R.id.url*/ });
setListAdapter(adapter);
}
Have you heard about gson (docs)?
public static final class Content {
#SerializedName("streamer") // you don't need to specify this, JFYI
String streamer;
#SerializedName("yt_length") // you don't need to specify this, JFYI
String yt_length;
}
public static final class Data {
#SerializedName("data")
List<Content> data;
}
public static void main (String[] args) {
Gson gson = new GsonBuilder().create();
Data data = gson.fromJson(jsonString, Data.class);
}
And remember, you cannot call network operations on UI thread! this is reason of what you have for now.
json data
[
-{
Cat_Id: 21
Cat_Title: "Electronics"
Cat_Description: null
Cat_Status: 0
Cat_CreatedBy: 0
Cat_CreatedDate: "0001-01-01T00:00:00"
Cat_UpdatedBy: 0
Cat_UpdatedDate: "0001-01-01T00:00:00"
}
Category class
public class Category {
public int Cat_Id;
public String Cat_Title = null;;
public Category() {
}
public int getCat_Id() {
return Cat_Id;
}
public void setCat_Id(int Cat_Id) {
this.Cat_Id = Cat_Id;
}
}
BaseActivity
public class BaseActivity extends Activity {
public ProgressDialog progressDialog;
public SharedPreferences prefs;
public JSONObject jsonObject;
public JSONObject jsonObject1;
public static String pref_setting = "Category_setting";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// TODO Auto-generated method stub
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading..");
prefs = PreferenceManager.getDefaultSharedPreferences(this);
Preferences.AppContext = this;
}
protected void onStop() {
super.onStop();
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
Soap
public class Soap {
// public static String BaseURL = "";
public static String BaseURL = "";
public static String imgURL = "";
public static String getSoapResponseByGet(String postFixOfUrl)
throws ClientProtocolException, IOException {
if (Preferences.AppContext != null
&& Preferences.isOnline(Preferences.AppContext)) {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(BaseURL + postFixOfUrl);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
String xmlString = EntityUtils.toString(entity);
return xmlString.toString();
} else {
return "{\"error\":{\"no_internet\":\"No internet connection\"}}";
}
}
public static String getSoapResponse(String postFixOfUrl)
throws ClientProtocolException, IOException {
if (Preferences.AppContext != null
&& Preferences.isOnline(Preferences.AppContext)) {
HttpPost httpPost = new HttpPost(BaseURL + postFixOfUrl);
StringEntity se = new StringEntity("", HTTP.UTF_8);
se.setContentType("text/xml");
httpPost.setHeader("Content-Type", "text/xml;charset=utf-8");
httpPost.setEntity(se);
HttpClient httpClient = new DefaultHttpClient();
BasicHttpResponse httpResponse = (BasicHttpResponse) httpClient
.execute(httpPost);
HttpEntity r_Entity = httpResponse.getEntity();
String xmlString = EntityUtils.toString(r_Entity);
return xmlString.toString();
} else {
return "{\"error\":{\"no_internet\":\"No internet connection\"}}";
}
}
public static String getSoapResponseByPost(String postFixOfUrl,
ArrayList<NameValuePair> nameValuePairs)
throws ClientProtocolException, IOException {
if (Preferences.AppContext != null
&& Preferences.isOnline(Preferences.AppContext)) {
HttpPost httpPost = new HttpPost(BaseURL + postFixOfUrl);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpClient httpClient = new DefaultHttpClient();
BasicHttpResponse httpResponse = (BasicHttpResponse) httpClient
.execute(httpPost);
HttpEntity r_Entity = httpResponse.getEntity();
String xmlString = EntityUtils.toString(r_Entity);
return xmlString.toString();
} else {
return "{\"error\":{\"no_internet\":\"No internet connection\"}}";
}
}
// ////////// api for Category //////////////
http://sharafdg.digitarabia.com/sharafdg/api/Category
public static String apiGetCategory() throws ClientProtocolException,
IOException {
String result = Soap.getSoapResponseByGet("api/Category");
Log.e("SOAP", result);
return result;
}
public static String apiGetstore(int catid, int brandid, int modelid,
String variant) throws ClientProtocolException, IOException {
String result = Soap.getSoapResponseByGet("api/stores/?catid=" + catid
+ "&brandid=" + brandid + "&modelid=" + modelid + "&variant="
+ variant);
Log.e("SOAPSTORE", "api/stores/?catid=" + catid);
Log.e("SOAPSTORE", "api/stores/?&brandid=" + brandid);
Log.e("SOAPSTORE", "api/stores/?&modelid=" + modelid);
Log.e("SOAPSTORE", "api/stores/?&variant=" + variant);
return result;
}
-------------- post method hoy to -----------------
http://kallapp.madword-media.co.uk/company.php?category_id=11
http://kallapp.madword-media.co.uk/categories.php
public static String apiGetCategory() throws ClientProtocolException,
IOException {
ArrayList<NameValuePair> alNameValuePairs = new
ArrayList<NameValuePair>();
String result = Soap.getSoapResponseByPost("categories.php",
alNameValuePairs);
return result;
}
public static String apiGetcompanies(String category_id)
throws ClientProtocolException, IOException {
ArrayList<NameValuePair> alNameValuePairs = new
ArrayList<NameValuePair>();
// NameValuePair nameValuePairs = new BasicNameValuePair("",
// category_id);
// alNameValuePairs.add(nameValuePairs);
String result = Soap.getSoapResponse("company.php?category_id="
+ category_id);
Log.e("SOAP", result);
return result;
}
public static String apiGetDepaName(String category_id, String
company_id)
throws ClientProtocolException, IOException {
ArrayList<NameValuePair> alNameValuePairs = new
ArrayList<NameValuePair>();
NameValuePair nameValuePair = new BasicNameValuePair("category_id",
category_id);
alNameValuePairs.add(nameValuePair);
nameValuePair = new BasicNameValuePair("company_id", company_id);
alNameValuePairs.add(nameValuePair);
String result =
Soap.getSoapResponseByPost("department.php?",alNameValuePairs);
return result;
}
Category_list
public class Category_list extends BaseActivity {
int currentCategoryid;
private ArrayList<Category> cat = new ArrayList<Category>();
ArrayList<String> list = new ArrayList<String>();
Spinner spinner;
Button btncompare;
private int catid;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// TODO Auto-generated method stub
setContentView(R.layout.activity_webservices);
spinner = (Spinner) findViewById(R.id.spinner);
btncompare = (Button) findViewById(R.id.btncompare);
spinner.setOnItemSelectedListener(new OnItemSelected());
new getCategoryTask().execute();
btncompare.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getBaseContext(), Store.class);
intent.putExtra("catid", catid);
startActivity(intent);
}
});
}
public class OnItemSelected implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// ((TextView) arg0.getChildAt(0)).setTextColor(Color.GREEN);
catid = cat.get(arg2).Cat_Id;
String cateid = String.valueOf(catid);
Log.e("cateid_category", cateid);
// new getBrandTask().execute();
}
public void onNothingSelected(AdapterView<?> arg0) {
}
}
private class getCategoryTask extends AsyncTask<Void, Void, Void> {
Category category;
String categoryJsonStr;
public getCategoryTask() {
category = new Category();
}
protected void onPreExecute() {
super.onPreExecute();
// progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
-----------------------admin email-pass-------------
JSONObject jsonObject = new JSONObject(userJsonStr);//
jsonUserArray.getJSONObject(i);
currentUserid = jsonObject.getInt("Use_Id");
if (currentUserid > 0) {
if (!jsonObject.isNull("Use_Id")) {
id = jsonObject.getInt("Use_Id");
}
}
--------------------kallapp---------
try {
Log.i("categoryJsonStr", categoryJsonStr);
JSONObject jsonObject = new JSONObject(categoryJsonStr);
JSONArray jsonCatArray = jsonObject.getJSONArray("categories");
for (int i = 0; i < jsonCatArray.length(); i++) {
Category objcategory = new Category();
jsonObject = jsonCatArray.getJSONObject(i);
--------------------------------------------------------------
try {
// categoryJsonStr = Soap.apiGetCategory();
Log.e("categoryJsonStr", categoryJsonStr);
JSONArray jsonCatArray = new JSONArray(categoryJsonStr);
Category category = new Category();
// category.Cat_Id = -1;
category.Cat_Title = "Select Category";
cat.add(category);
list.add(category.Cat_Title);
for (int i = 0; i < jsonCatArray.length(); i++) {
Category objcategory = new Category();
JSONObject jsonObject = jsonCatArray.getJSONObject(i);
currentCategoryid = jsonObject.getInt("Cat_Id");
if (!jsonObject.isNull("Cat_Title")) {
objcategory.setCat_Title(jsonObject
.getString("Cat_Title"));
}
if (!jsonObject.isNull("Cat_Id")) {
objcategory.setCat_Id(jsonObject.getInt("Cat_Id"));
}
cat.add(objcategory);
list.add(objcategory.Cat_Title);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
public void onPostExecute(Void result) {
super.onPostExecute(result);
// progressDialog.dismiss();
spinner.setAdapter(new ArrayAdapter<String>(Category_list.this,
android.R.layout.simple_spinner_item, list));
spinner.setSelection(0, true);
}
}
}
-------------more than one item fill--------
store_lists.add(objStore_list);
public void onPostExecute(Void result) {
super.onPostExecute(result);
store_adapter = new Store_adapter(Store.this, store_lists);
lv_store.setAdapter(store_adapter);
store_adapter.notifyDataSetChanged();
}
Preferences
public class Preferences {
public static Context AppContext = null;
public static String categoryid;
public static boolean isOnline(Context c) {
ConnectivityManager cm = (ConnectivityManager) c
.getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().isConnectedOrConnecting();
}
}
Store_adapter
private Context mContext;
private int ImageCount;
private ArrayList<Store_list> store_lists = new ArrayList<Store_list>();
public ImageLoader imageLoader;
ImageView imgsave, imgpackage, img_up_arrow, img_dun_arrow;
TextView txtsave;
RelativeLayout relatv;
public Store_adapter(Context c, ArrayList<Store_list> store_lists) {
mContext = c;
this.store_lists = store_lists;
this.ImageCount = store_lists.size();
imageLoader = new ImageLoader(c);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
// ImageCount = store_lists.size();
return this.ImageCount;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
this.ImageCount = store_lists.size();
}
public void remove(int position) {
store_lists.remove(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View vi = inflater.inflate(R.layout.storelist, parent, false);
TextView name = (TextView) vi.findViewById(R.id.txtprise);
ImageView imgview = (ImageView) vi.findViewById(R.id.imgve);
Store_list list = store_lists.get(position);
imageLoader.DisplayImage(list.Store_logo, imgview);
name.setText(String.valueOf(list.Mod_Price));
return vi;
}
}
menifestfile
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"
/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
/>
public static String getSoapResponse(String postFixOfUrl) {
try {
if (General.AppContext != null
&& General.isOnline(General.AppContext)) {
HttpGet httpget = new HttpGet(BaseURL + postFixOfUrl);
Log.i("SOAP", "URI:" + BaseURL + postFixOfUrl);
httpget.setHeader("Content-Type",
"application/json;charset=utf-8");
HttpClient httpclient = new DefaultHttpClient();
BasicHttpResponse httpResponse = (BasicHttpResponse) httpclient
.execute(httpget);
HttpEntity r_entity = httpResponse.getEntity();
String xmlString = EntityUtils.toString(r_entity);
return xmlString.toString();
} else {
// return
// "[{\"erorr\":{\"no_internet\":\"No internet connection\"}}]";
if (General.AppActivity != null) {
General.AppActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(
General.AppContext,
General.AppContext
.getResources()
.getString(
R.string.no_internet_connection),
Toast.LENGTH_SHORT).show();
}
});
}
return null;
}
} catch (Exception e) {
HandleException.catchException(e, true);
}
return null;
}
// post method
public static String getSoapResponseByPost(String postFixOfUrl,
ArrayList<NameValuePair> nameValuePairs)
throws ClientProtocolException, IOException {
try {
if (General.AppContext != null
&& General.isOnline(General.AppContext)) {
HttpPost httppost = new HttpPost(BaseURL + postFixOfUrl);
Log.i("SOAP", "URI:" + BaseURL + postFixOfUrl);
// httppost.setHeader("Content-Type",
// "text/html;charset=utf-8");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,
"UTF-8"));
HttpClient httpclient = new DefaultHttpClient();
BasicHttpResponse httpResponse = (BasicHttpResponse) httpclient
.execute(httppost);
HttpEntity r_entity = httpResponse.getEntity();
String xmlString = EntityUtils.toString(r_entity);
return xmlString.toString();
} else {
// return
// "[{\"erorr\":{\"no_internet\":\"No internet connection\"}}]";
if (General.AppActivity != null) {
General.AppActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(
General.AppContext,
General.AppContext
.getResources()
.getString(
R.string.no_internet_connection),
Toast.LENGTH_SHORT).show();
}
});
}
return null;
}
} catch (Exception e) {
HandleException.catchException(e, true);
}
return null;
}
public static String getSoapResponseForImage(String postFixOfUrl,
List<NameValuePair> nameValuePairs,
List<NameValuePair> filenameValuePairs) {
String xmlString = null;
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(BaseURL + postFixOfUrl);
try {
MultipartEntity entity = new MultipartEntity();
for (int index = 0; index < filenameValuePairs.size(); index++) {
File myFile = new File(filenameValuePairs.get(index).getValue());
if (myFile.exists()) {
FileBody fileBody = new FileBody(myFile);
entity.addPart(filenameValuePairs.get(index).getName(),
fileBody);
}
}
for (int index = 0; index < nameValuePairs.size(); index++) {
entity.addPart(nameValuePairs.get(index).getName(),
new StringBody(nameValuePairs.get(index).getValue(),
Charset.forName("UTF-8")));
}
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
HttpEntity r_entity = response.getEntity();
xmlString = EntityUtils.toString(r_entity);
} catch (IOException e) {
e.printStackTrace();
}
Log.d("SOAP ", "Result : " + xmlString.toString());
return xmlString.toString();
}
public class ParsedResponse {
public Object o;
public boolean error = false;
}
public class General {
public static Context AppContext = null;
public static Activity AppActivity = null;
public static boolean isOnline(Context c) {
ConnectivityManager cm = (ConnectivityManager) c
.getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().isConnectedOrConnecting();
}}
public class BaseActivity extends Activity {
protected SharedPreferences prefs;
public ProgressDialog progressDialog;
General.AppContext = getApplicationContext();
General.AppActivity = BaseActivity.this;
prefs = PreferenceManager.getDefaultSharedPreferences(this);}
public class ErrorMgmt {
private Boolean error;
private String errorMessage;
private String exceptionMessage;
public ErrorMgmt(String exceptionMessage) {
error = false;
errorMessage = "";
this.exceptionMessage = exceptionMessage;
}
public ErrorMgmt() {
error = false;
errorMessage = "";
exceptionMessage = "";
}
public String getErrorMessage() {
if (error) {
if (errorMessage.equals("")) {
return exceptionMessage;
} else {
return errorMessage;
}
}
return null;
}
#SuppressWarnings("rawtypes")
public Boolean strError(String JsonResponse) {
this.error = false;
errorMessage = "";
try {
JSONObject objJson = new JSONObject(JsonResponse);
String strJson = objJson.getString("JsonResponse");
if(!strJson.equals("Please enter valid email")) {
this.error = true ;
errorMessage = "";
} else {
this.error = false;
}
} catch (JSONException e) {
this.error = true;
errorMessage = "";
HandleException.catchException(e, true);
}
return this.error;
}
#SuppressWarnings("rawtypes")
public Boolean isObjError(String JsonResponse) {
this.error = false;
errorMessage = "";
try {
JSONObject objJson = new JSONObject(JsonResponse);
if (objJson != null && !objJson.isNull("error") ) {
this.error = true;
Iterator IError = objJson.keys();
errorMessage = "";
while (IError.hasNext()) {
String key = (String) IError.next();
errorMessage += objJson.getString(key) + "\n";
}
} else if (objJson != null && !objJson.isNull("statusCode")) {
Integer statusCode = objJson.getInt("statusCode");
if (statusCode > 200) {
this.error = true;
} else {
this.error = false;
}
} else {
this.error = false;
}
} catch (JSONException e) {
this.error = true;
errorMessage = "";
HandleException.catchException(e, true);
}
return this.error;
}
#SuppressWarnings("rawtypes")
public Boolean isError(String JsonResponse) {
this.error = false;
errorMessage = "";
try {
JSONArray arrJson = new JSONArray(JsonResponse);
if (!arrJson.isNull(0) && !arrJson.getJSONObject(0).isNull("erorr")) {
this.error = true;
JSONObject objError = arrJson.getJSONObject(0);
Iterator IError = objError.keys();
errorMessage = "";
while (IError.hasNext()) {
String key = (String) IError.next();
errorMessage += objError.getString(key) + "\n";
}
} else if (!arrJson.isNull(0)
&& !arrJson.getJSONObject(0).isNull("statusCode")) {
Integer statusCode = arrJson.getJSONObject(0).getInt(
"statusCode");
if (statusCode > 200) {
this.error = true;
} else {
this.error = false;
}
} else {
this.error = false;
}
} catch (JSONException e) {
this.error = true;
errorMessage = "";
HandleException.catchException(e, true);
}
return this.error;
}
public void SetForsedError(Boolean val) {
error = true;
}
}
// Api for register with Email
public static ParsedResponse apiRegister(String name, String email,
String password) throws Exception {
ArrayList<NameValuePair> alNameValuePairs = new ArrayList<NameValuePair>();
NameValuePair nameValuePair = new BasicNameValuePair("name", name);
alNameValuePairs.add(nameValuePair);
nameValuePair = new BasicNameValuePair("email", email);
alNameValuePairs.add(nameValuePair);
nameValuePair = new BasicNameValuePair("password", password);
alNameValuePairs.add(nameValuePair);
// nameValuePair = new BasicNameValuePair("fb_uid", "");
// alNameValuePairs.add(nameValuePair);
String result = Soap.getSoapResponseByPost("user/register",
alNameValuePairs);
Log.e("apiRegister", result);
ErrorMgmt errMgmt = new ErrorMgmt(General.AppContext.getResources()
.getString(R.string.error_loading_data));
ParsedResponse p = new ParsedResponse();
p.error = false;
if (result != null && !result.equals("")) {
JSONObject jObject = new JSONObject(result);
String code = "";
if (!jObject.isNull("statusCode")) {
code = jObject.getString("statusCode");
}
if (code.equals("200")) {
JSONArray jsonArray = jObject.getJSONArray("User");
if (jsonArray.length() > 0) {
ArrayList<UserData> arrayList = new ArrayList<UserData>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
UserData objUserData = new UserData();
if (!jsonObject.isNull("uid")) {
objUserData.uid = jsonObject.getString("uid");
}
if (!jsonObject.isNull("name")) {
objUserData.name = jsonObject.getString("name");
}
if (!jsonObject.isNull("email")) {
objUserData.email = jsonObject.getString("email");
}
if (!jsonObject.isNull("password")) {
objUserData.password = jsonObject
.getString("password");
}
if (!jsonObject.isNull("created_date")) {
objUserData.created_date = jsonObject
.getString("created_date");
}
if (!jsonObject.isNull("status")) {
objUserData.status = jsonObject.getString("status");
}
if (!jsonObject.isNull("fb_uid")) {
objUserData.fb_uid = jsonObject.getString("fb_uid");
}
if (!jsonObject.isNull("account_type")) {
objUserData.account_type = jsonObject
.getString("account_type");
}
if (!jsonObject.isNull("profile_img")) {
objUserData.profile_img = jsonObject
.getString("profile_img");
}
if (!jsonObject.isNull("birthdate")) {
objUserData.birthdate = jsonObject
.getString("birthdate");
}
if (!jsonObject.isNull("city")) {
objUserData.city = jsonObject.getString("city");
}
JSONArray jsonArray2 = jsonObject
.getJSONArray("usersubscribe");
if (jsonArray2.length() > 0) {
for (int i1 = 0; i1 < jsonArray2.length(); i1++) {
JSONObject jsonObject2 = jsonArray2
.getJSONObject(i1);
if (!jsonObject2.isNull("isSubscribe")) {
objUserData.isSubscribe = jsonObject2
.getString("isSubscribe");
}
if (!jsonObject2.isNull("amount")) {
objUserData.amount = jsonObject2
.getString("amount");
}
}
}
arrayList.add(objUserData);
p.o = arrayList;
}
} else {
errMgmt = new ErrorMgmt(General.AppActivity.getResources()
.getString(R.string.err_norecords));
errMgmt.SetForsedError(true);
p.o = errMgmt;
p.error = true;
}
}
if (code.equals("401")) {
errMgmt = new ErrorMgmt(General.AppActivity.getResources()
.getString(R.string.allready_regi));
errMgmt.SetForsedError(true);
p.o = errMgmt;
p.error = true;
}
} else {
errMgmt = new ErrorMgmt(General.AppActivity.getResources()
.getString(R.string.err_norecords));
errMgmt.SetForsedError(true);
p.o = errMgmt;
p.error = true;
}
return p;
}
// Login with Facebook
private class GetFacebookLogin extends AsyncTask<Void, Void, Void> {
private ParsedResponse p = null;
private String message = "";
private Boolean error = false;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
p = new ParsedResponse();
p = Soap.apiUserLoginFacebook(fbID);
if (p.error) {
ErrorMgmt errmgmt = (ErrorMgmt) p.o;
message = errmgmt.getErrorMessage();
error = true;
} else {
arrayList.clear();
arrayList.addAll((ArrayList<UserData>) p.o);
error = false;
}
} catch (Exception e) {
message = "problem in loading data";
error = true;
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
progressDialog.dismiss();
if (error) {
new AlertDialog.Builder(Register_Login_Screen.this)
.setMessage(message)
.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
}).show();
} else {
UserData objUserData = new UserData();
for (int i = 0; i < arrayList.size(); i++) {
objUserData = arrayList.get(i);
}
String profileImage = "";
try {
URL image_value = new URL("http://graph.facebook.com/"
+ fbID + "/picture?height=150&width=150");
profileImage = String.valueOf(image_value);
Log.e("fb_image_path", "" + image_value);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Editor e = prefs.edit();
e.putBoolean(General.PREFS_login, true);
e.putString(General.PREFS_Uid, objUserData.uid);
e.putString(General.PREFS_name, objUserData.name);
e.putString(General.PREFS_email, objUserData.email);
e.putString(General.PREFS_fb_uid, objUserData.fb_uid);
e.putString(General.PREFS_logintype, General.PREFS_valuefblogin);
if (objUserData.profile_img != null
&& !objUserData.profile_img.equals("")) {
e.putString(General.PREFS_profile_img,
objUserData.profile_img);
} else {
e.putString(General.PREFS_profile_img, profileImage);
}
e.putString(General.PREFS_account_type,
objUserData.account_type);
e.putString(General.PREFS_birthdate, objUserData.birthdate);
e.putString(General.PREFS_city, objUserData.city);
e.putString(General.PREFS_subscribed, objUserData.isSubscribe);
e.putString(General.PREFS_amount, objUserData.amount);
String[] strings = null;
for (int i = 0; i < objUserData.screenerArr.size(); i++) {
String queString = objUserData.screenerArr.get(i);
strings = queString.split(",");
String question1 = strings[0];
e.putString("RosaRosa_screener_question" + (i + 1),
question1);
e.putBoolean("RosaRosa_screener_ans" + (i + 1), true);
String ans1 = strings[1];
e.putString(
"RosaRosa_screener_question" + (i + 1) + "_ans",
ans1);
Log.e("question", "" + question1 + ans1);
}
e.commit();
Toast.makeText(Register_Login_Screen.this, R.string.succ_login,
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Register_Login_Screen.this,
Personal_Stylist_Activity.class);
startActivity(intent);
finish();
}
}
}

Categories

Resources