This problem freak me out
I have an application and now i want to transer data between client android application and localhost tomcat 7 server, i did that many times ago, now when i want to send data from client to server it works well and i can see the data on the server, but something happend and the android application is trying to trigger an activity from another project i deleted that project then still try to trigger activty form another project
my actiivty name is "Signup", and the android client trying to trigger activiteis with the same name from another projects.
as in log :
NumberFormatException: unable to parse
'[Lorg.apache.http.Header;#44ee4c10' as integer
means you are trying to parse wrong string to Integer . wrap casting code inside try/catch block to avoid NumberFormatException as :
String str_NumberOfCities="";
Header[] headers = response.getAllHeaders();
for (int i=0; i < headers.length; i++) {
Header h = headers[i];
Log.i(TAG, "Header names: "+h.getName());
if(h.getName().toLowerCase().contains("NumberOfCities".toLowerCase()){
str_NumberOfCities=h.getValue();
}
Log.i(TAG, "Header Value: "+h.getValue());
}
int numberOfCities=0;
try {
numberOfCities = Integer.parseInt(str_NumberOfCities);
} catch (NumberFormatException e) {
numberOfCities=0;
}
Data.cities = new String[numberOfCities];
///....your code
Related
I'm using Volley and looking at this ( http://www.androidhive.info/2014/09/android-json-parsing-using-volley/ ) tutorial, but I don't know how to make it work. Using ObjectJSON, error says "it can't be converted to Array" and if I use ArrayJSON method it doesn't found database elements.
My urlJSON - http://smkbaig.esy.es/get_info_test.php
Your JSON following the php link you provided starts with { and as the tutorial said, that's a JSON Object, followed by an array called "receptai".
If you have followed the tutorial correctly till the end, it should work using
makeJsonArrayRequest()
You really need to paste your code here so that we could help further.
What you might want to do first is follow the tutorial exactly the way it was presented, and if you get responses successfully, then start experimenting and changing. I see you are using your own JSON instead of coding for both JsonArrays and JsonObjects and seeing both buttons get functional.
Thnaks #iBobb for answer, it helped me.
Here is how it worked out:
try {
JSONArray ja = response.getJSONArray("receptai");
for (int i = 0; i < ja.length(); i++) {
JSONObject jsonObject = ja.getJSONObject(i);
rec = new Receptas();
rec.setPav(jsonObject.getString("pav"));
rec.setApras(jsonObject.getString("apras"));
rec.setIngred_sk(jsonObject.getString("ingred_sk"));
recList.add(rec);
}
// ListView
// txtResponse.setText(data);
} catch (JSONException e) {
e.printStackTrace();
}
I am sagar, i am trying to implement the Parse Push-Notification in android using REST API (Service), and i am almost got success in implement the Push-Notification in Xamarin-Android using REST API. But i got stuck with one part in sending the Data into REST service. I trying to pass the ParseObject in service, but the in parse table there is a need of Object,(). I have tried to pass the ParseObject as below:
JsonConvert.SerializeObject(ParseUser.CurrentUser)
It convert ParseObject into array and array is not accepted in table and ,i got failed to save it in table. because there i a need of object.
I need solution or suggestion from developer guys. Yours help will be appreciated. I am trying the below code to achieve the result.
public static void RegisterPush(string regristrationId)
{
if (regristrationId != null) {
string appID = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
string restID = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
string masterID = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
try {
var client = new RestClient ("https://api.parse.com");
var request = new RestRequest ("1/installations", RestSharp.Method.POST);
request.AddHeader ("Accept", "application/json");
request.AddHeader ("X-Parse-Application-Id", appID);
request.AddHeader ("X-Parse-REST-API-Key", restID);
request.Credentials = new NetworkCredential (appID, masterID);
request.Parameters.Clear ();
Console.Error.WriteLine ("ParseUser.CurrentUser-->"+ (ParseObject) ParseUser.CurrentUser);
//JsonConvert.SerializeObject(ParseUser.CurrentUser)
string strJSONContent = "{\"user\" :"+ JsonConvert.SerializeObject(ParseUser.CurrentUser)+",\"owner\":\"" + ParseUser.CurrentUser.ObjectId + "\",\"deviceType\":\"android\",\"GCMSenderId\":\"1234567890\",\"appName\":\"abcdefgh\",\"pushType\":\"gcm\",\"deviceToken\":\"" + regristrationId + "\"}";
Console.Error.WriteLine("json string-->"+ strJSONContent);
request.AddParameter ("application/json", strJSONContent, ParameterType.RequestBody);
client.ExecuteAsync (request, response => {
Console.Error.WriteLine ("response for android parse installation-->" + response.Content);
});
} catch (Exception ex) {
Console.WriteLine (ex.Message);
}
}
}`
Output:{"user" :[{"Key":"dealOffered","Value":4},{"Key":"dealRequested","Value":5},{"Key":"displayName","Value":"Cook"},{"Key":"email","Value":"lorenzo#gmail.com"},{"Key":"firstName","Value":"Lorenzo"},{"Key":"lastName","Value":"Cook"},{"Key":"mobileNumber","Value":9999999999.0},{"Key":"picture","Value":{"IsDirty":false,"Name":"tfss-afd25c29-6679-4843-842c-fe01f7fcf976-profile.jpg","MimeType":"image/jpeg","Url":"http://files.parsetfss.com/profile.jpg"}},{"Key":"provider","Value":"password"},{"Key":"userType","Value":"Merchant"},{"Key":"username","Value":"merchant#sailfish.com"},{"Key":"zipCode","Value":2342343}],"owner":"3cF1vHUXkW","deviceType":"android","GCMSenderId":"1234567890123","appName":"Sailfish","pushType":"gcm","deviceToken":"APA91bE3bsTIInQcoloOBE4kdLVVHVTRVtNyA1A788hYSC15wAVu8mUg-lwk7ZPk370rngrK7J6OoLmiM9HRr1CGPaBo6LCNrSUL7erBku4vepaFFkQzgqS6BcAemp"}
Error:{"code":111,"error":"invalid type for key user, expected *_User, but got array"}
maven
I found the solution in , parse xamarin docs, in one query , the way is simple, but i little bit hard to found out.
The issue is with the data passing in json format in REST, to pass any pointer using REST API, use as below.
The solution is as below:
`{
"user":{
"__type":"Pointer",
"className":"_User",
"objectId":"qYvzFzGAzc"
},
"owner":"qYvzFzGAzc",
"deviceType":"android",
"GCMSenderId":"123456789",
"appName":"NiceApp",
"pushType":"gcm",
"deviceToken":"APA91bFeM10jdrCS6fHqGGSkON17UjEJEfvJEmGpRM-d6hq3hQgDxKHbyrqAIxMnEGgbLEZf0E9AllHxiQQQCdEFiNMF1_A8q0n9tGpBE5NKhvS2ZGJ9PZ7585puWqz_1Z1EjSjOvgZ1LQo708DeL2KzA7EFJmdPAA"
}`
It looks like your column user is set up wrong. It should show as a Pointer<_User> not Pointer
If you load this class in your Data Browser, is the "user" key defined as a string, or a Pointer <_User>
This error seems to indicate that this is a string column, which is why the Parse.User object is not being accepted as a valid value. You might have tried setting a string on this key before, which in turn type-locked the "user" key as a string column.
Found it on the examples given on this page - https://www.parse.com/docs/rest
Have you check your REST API connection while passing ParseObject?
Because your error says:
Error:{"code":111,"error":"invalid type for key user, expected *_User, but got array"}
Here "code":111This error code comes when server refuse for connection
I am using json request for logging in and displaying messages pertaining to the user .But if I make the same request from the browser it still works. I am using PHP-MYSQL for my App .
I do not have any website so I will need the answer for the app itself.
I am using facebook sdk with android app so I dont have any passwords. I would like to secure the chat msgs between the users and user data profile when it is called.Thats it.
My questions are:
How do I make sure the call is made within the app only?
How do I secure the call when some tries to copy and paste the code in the browser ?
3.Have timeout for the message created after 10 secs.So the same url and msg cannot be reused.
I have http call like http:/example.com/login=emailId;
get msgs: http:/example.com/getMsgs/user=uiniqueNo;
I have provided the above links as I am using in the app and its working fine but is not secure.
Please suggest me some documents and process.I have checked this link Protect HTTP request from being called by others but it was not clear .Please suggest me any tutorial which has the above requirements . Thanks in Advance.I really appreciate the help.
public class CustomizedListView extends Activity {
// All static variables
static final String URL = "http://example.com/getmsgs/userno=123";
// XML node keys
static final String KEY_SONG = "song"; // parent node
static final String KEY_ID = "id";
static final String KEY_TITLE = "title";
static final String KEY_ARTIST = "artist";
static final String KEY_DURATION = "duration";
static final String KEY_THUMB_URL = "thumb_url";
ListView list;
LazyAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
JSONObject json = JSONfunctions.getJSONfromURL(URL);
try {
JSONObject arr2 = json.getJSONObject("feed");
JSONArray arr = arr2.getJSONArray("entry");
for (int i = 0; i < arr.length(); i++) {
JSONObject e1 = arr.getJSONObject(i);
JSONArray arr3 = e1.getJSONArray("im:image");
JSONObject arr8 = e1.getJSONObject("im:name");
JSONObject arr10 = e1.getJSONObject("im:artist");
JSONObject e12 = arr3.getJSONObject(0);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
map.put(KEY_THUMB_URL, e12.getString("label"));
map.put(KEY_ARTIST, arr8.getString("label"));
map.put(KEY_TITLE, arr10.getString("label"));
// adding HashList to ArrayList
songsList.add(map);
}
} catch (JSONException e) {
// Log.e("log_tag", "Error parsing data "+e.toString());
Toast.makeText(getBaseContext(),
"Network communication error!", 5).show();
}
list=(ListView)findViewById(R.id.list);
// Getting adapter by passing xml data ArrayList
adapter=new LazyAdapter(this, songsList);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#SuppressWarnings("unchecked")
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
HashMap<String, String> o = (HashMap<String, String>) list.getItemAtPosition(position);
Toast.makeText(CustomizedListView.this, "ID '" + o.get("KEY_TITLE") + "' was clicked.", Toast.LENGTH_SHORT).show();
}
});
}
}
In the above code anyone can guess usersno but how do I secure that no 123 in the app and in the php server .So that even if sniffer program is used and and reverse engineered to get code from apk file the data still is protect and encryption should be deep in OS which users cannot break and hence I can decrypt the code in server php and user will have no way to randomly type anything as 123.
<?php
$strno=$_GET['strno'];
if (isset($strno))
{
$connect=mysql_connect("localhost","test","test") or die ('Connection error!!!');
mysql_select_db("test") or die ('Database error!!!');
$query=mysql_query("select sno FROM users where strno='$strno';");
while($row = mysql_fetch_assoc($query))
{
$jsonoutput='{"json":{
"msg_sub":"'.$row['msg_sub'].'",
}}';
}
}
echo trim($jsonoutput);
mysql_close($connect) or die ('Unable to close connection-error!!!');
}
?>
Ok there is no way to actually perfectly protect this system unless you use https to transmit data between your api and your js client.
This is what you do:
First create a user login system, username/password table on your database side
Next create a form for the user to login
Whenever a user tries to access the api your server will check if it has a session set for that user, they will either have to login or pass an existing session id which will grant them access
Next is to buy an https certificate that will ensure your data is transmitted securely
Now on each request to the api, the server always checks if they user has sent a valid SESSION ID, if not, it will simply redirect them to a login page
This is pretty much the only way you can add security to your system. The most important part is the https cert. Without this, it doesnt matter how good a user/password is, it can still be compromised.
EDIT
Here is some sample code to get you started. This code is not tested and its just there to give you an idea. You can read all about sessions here.
<?php
/*
like I said earlier, you need to have a "login" screen on your app
- when the user clicks login it POSTS the request back here
*/
if(isset($_SESSION['username'])){
//the username is in the session so it means
//theyre already logged in
//not sure what strno is doing but you can do that here
$strno=$_GET['strno'];
if (isset($strno))
{
$connect=mysql_connect("localhost","test","test") or die ('Connection error!!!');
mysql_select_db("test") or die ('Database error!!!');
$query=mysql_query("select sno FROM users where strno='$strno';");
while($row = mysql_fetch_assoc($query))
{
$jsonoutput='{"json":{
"msg_sub":"'.$row['msg_sub'].'",
}}';
}
}
echo trim($jsonoutput);
mysql_close($connect) or die ('Unable to close connection-error!!!');
}else if(isset($_POST) && isset($_POST['username']) && isset($_POST['password'])){
//log them in
//query ur database to see if the user exists
//if you get a row back then store that row in the session like
//note: this is just example code
if(/*user is in database, get the row....*/){
session_start();
$_SESSION['username'] = $row['username'];
}
}else{
die("Access Denied");
}
?>
There are two options to achieve this. First thing is using GET method, you can create a specific params on your server side which you are looking for. For example from your android app you are sending http://www.my-backend.com/api/test_api?my_secure_code=thisIsTestString and server returns the right response, but if you send http://www.my-backend.com/api/test_api?my_secure_code=thatsAnotherString , the param value you are searching for in the request is not thisIsTestString, so you should return error message.
In my opinion the second way to achieve this is better, because using GET is not thats ecure in my opinion.It's easier than using POST. In that case you will have to send my_secure_param as post param, which you can use by typing in your browser (there is still a way to achieve this by browser by installing plugin for post request). So I think the best solution here is to use POST request while connection to back-end sending some hashed string using MD5 or SHA1 (at least that's the way we are securing connection with our server + some more extras).
Edit: Regarding comments, the way you can achieve this is by creating some kind of identification for the specific user on your server, not trusting facebook. It's just a proposal...for example you can get the id user from facebook and create a unique hashed id which you will store in your server and everytime you are sending requests from your app, you have to send that unique id, which will be created in app in the same way used to create it on the server. And you will have to check for that hash everytime someone sends message if that match, if not just return error..and just don't forget, use POST requests instead of GET! There is no way to achieve something like this without changing some codes in your server's backend.
Tried to use ACRA in my app, but I can't get the google drive or the email working (in google drive I don't know how to create the form from the template, email tells me there is no such email address even though I am sending from the same email address). I would rather get the google drive spreadsheet thing working or better yet - if there is a ready-to-use script for free web host that I can use to get the reports. Anyone knows of such a script?
EDIT: I need a php one...
Looks like ACRA uses a simple post. What language do you need it in? For asp.net:
protected void Page_Load(object sender, EventArgs e)
{
StringBuilder err = new StringBuilder();
foreach (string name in Request.Form)
{
err.AppendLine(name + ": " + Request.Form[name]);
}
TextWriter tw = null;
try
{
tw = new StreamWriter("f:\\errorLogs\\error_" + DateTime.Now.Ticks + ".txt");
tw.WriteLine(err.ToString());
}
catch (Exception) { }
finally
{
if(tw != null)
tw.Close();
}
}
Since you are using a "free web host", the location probably isn't valid for you, but this should at least get you pointed in the right direction. There is another post which is similar to yours. Most free web hosts use php.
EDIT:
Here is a basic PHP script (Not tested, but seems OK to me. My PHP is a bit rusty):
<?php
$file = 'postData.txt';
$arr= $_POST;
$fp = fopen($file, 'w') or die('Could not open file!');
foreach ($arr as $key => $value) {
$toFile = "Key: $key; Value: $value \n";
// write to file
fwrite($fp, "$toFile") or die('Could not write to file');
}
// close file
fclose($fp);
?>
I had a PHP API which showed a JSON Array, which I then read into an Android Application.
I since moved servers and the android application broke.
I assumed it was the Authentication and thought I would re-build the Android application (Was my first application and thought a re-write could make things better)
For some reason I am now getting this exception error
I read somewhere that I need to parse JSON_FORCE_OBJECT in the PHP json_encode
json_encode($arrMyData, JSON_FORCE_OBJECT);
But I am running PHP 5.2 (Options parameter came out in PHP 5.3)
My code for you to rip into
private void displayAllStories(){
String line;
int intNumStories = 0;
JSONObject arrAllStories;
LinearLayout storiesLayout = (LinearLayout) findViewById(R.id.lyoutStoriesMain);
storiesLayout.removeAllViewsInLayout();
try {
while((line = this.jsonResult.readLine()) != null){
JSONObject arrStories;
arrStories = new JSONObject(line.trim());
intNumStories = Integer.parseInt(arrStories.optString("NumStories"));
arrAllStories = arrStories.getJSONObject("StoryData");
this.strDebug += "We have "+intNumStories+"\n";
}
} catch (IOException e) {
this.strDebug += "Error (3) "+e.getLocalizedMessage()+"\n";
} catch (JSONException e) {
this.strDebug += "Error (4) "+e.getLocalizedMessage()+"\n";
}
}
And the encoded data from the website
{
"NumStories":1,
"StoryData":{
"Story0":{
"ID":"1020",
"OWERNAME":"Alicia",
"STORYMAIN":"Good evening my son was born with bilateral club feet. When he was a week old we started serial casting once a week for 3 months and then he was placed in braces for the next 6 months for a 23 hour period and then for the next 3 months just durning the night. This last visit the doctor said that he needs to have his tendons lengthened and he will go back into cast. After reading all of these articles I am a little scared on what will be best for him. It sounds like the risk of having the surgery are just as heavily weighed as just keeping him in AFO\\'s till he can make his own decision. I would like all advice whether it be positive or negative. Thank you in advance for your help.",
"STORYBRIEF":"Need reassurance that tendon lengthening is the best decision.",
"ADDEDDATE":"2011-12-12 00:51:16",
"CURRENTSTATUS":"n"
}
}
}
Sorry I should add, the code before this which procudes jsonResult is as follows
try{
URL url = null;
URLConnection urlConn = null;
InputStreamReader jsonIsr = null;
BufferedReader jsonBr = null;
//this.strDebug += "URL is "+this.strURL+"\n";
url = new URL(this.strURL);
urlConn = url.openConnection();
jsonIsr = new InputStreamReader(urlConn.getInputStream());
jsonBr = new BufferedReader(jsonIsr, 8192);
this.jsonResult = jsonBr;
return true;
}catch(MalformedURLException e){
this.strDebug += "JSON Error (1) "+e.getLocalizedMessage()+"\n";
}catch(IOException e){
this.strDebug += "JSON Error (2) "+e.getLocalizedMessage()+"\n";
}
}else{
strDebug = "NO URL Passed to JSON\n";
}
// EDIT 2
For those who asking
The error is as the title says
Error (4) A JSONObject text must being with '{' at character 1 of {"NumStories":1, "StoryData":........
Your code assumes that whole JSON data comes on one line: it iterates with readLine() but creates a new JSON object every time.
You are reading the data line by line and trying to convert each line into a JSON object. That won't work because a single line just contains a fragment of a complete JSON object.
I don't know what type jsonResult has. But you'll probably want to read the whole thing at once.
Your old web application probably produced JSON data without line break so a single line would contain a full JSON object.
i think you read the json file line by line and pass to the json object you should like this way the whole string you have to pass to the json object for parsing than only you getting the json
JSONObject arrStories = new JSONObject(jsonResult);
now get the object like this way
intNumStories = Integer.parseInt(arrStories.getString("NumStories"));
This code is going to break, if object takes more than one line (apparemtly it does). Your choices are:
Collect all the strings into string builder, the parse from this string ( http://developer.android.com/reference/org/json/JSONTokener.html )
Take GSON or my databinding layer ( https://github.com/ko5tik/jsonserializer ) and just parse stream into object.