This question already has answers here:
Only the original thread that created a view hierarchy can touch its views ERROR
(2 answers)
Closed 8 years ago.
I have an AsyncTask class inside my main activity. This class parses a JSON Object and then it sets the texts on some UI Components like TextViews, EditTexts etc. The problem is that when it sets the text on the first TextView then it stops. It will not give an error but the "Only the original thread that created a view hierarchy can touch its views" exception which actually means that you cannot affect any UI components through the AsynTask. I read that this could be done through a Runnable thread but i am not familiar how this can be done in my code. Any suggestions will be more than welcomed!!Thank you all!!
public class PostDataAsyncTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
// do stuff before posting data
}
#Override
protected String doInBackground(String... params) {
String postResponse = "";
TextView txt_class = (TextView) findViewById(R.id.txt_class);
TextView v_points = (TextView) findViewById(R.id.txt_points);
//EditText name = (EditText) findViewById(R.id.fname);
try {
// url where the data will be posted
String postReceiverUrl = "http://server.com/Json/consumer.php";
Log.v(TAG, "postURL: " + postReceiverUrl);
// HttpClient
HttpClient httpClient = new DefaultHttpClient();
// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);
// add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("ConsumerID", "52"));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// execute HTTP post request
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
// Convert response to String
//String result = EntityUtils.toString(response.getEntity());
// TEST
postResponse = EntityUtils.toString(resEntity).trim();
// CONVERT RESPONSE STRING TO JSON Object
JSONObject json = new JSONObject(postResponse);
// Get the JSONArray "Consumer"
JSONArray ja = json.getJSONArray("Consumer");
//List<String> detailsList = new ArrayList<String>();
// Creating the array that will hold the json items
String[] info = new String[ja.length()];
// Loop through all fields
for (int i = 0; i < ja.length(); i++) {
JSONObject c = ja.getJSONObject(i);
// Storing each json item in variable
String id = c.getString("userid");
String fname = c.getString("userfullname");
String tel1 = c.getString("tel1");
String email = c.getString("email");
String address = c.getString("address");
String county = c.getString("county");
String country = c.getString("country");
String rpoints = c.getString("RedeemPoints");
String level = c.getString("Level");
Log.v(TAG, "User ID: " + id + "\n"+ "Username: "+ fname + "\n"+ "Redeem points: "+rpoints + "\n"+ "Level: "+level);
txt_class.setText("Domotel "+ level+" Member");
v_points.setText("TestTestTest");
}
//Log.v(TAG, "Testing response: " + postResponse);
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return postResponse;
}
You have to update your UI in the onPostExecute of your AsyncTask.
Related
I am developing and I want to show user register or not. Following is my code in this it shows correct response in Logcat but not show the message on app side(i.e registration success or registration failed message).I am trying to parse response but logcat shows message is "org.json.JSONException: No value for responsetypes"
How do I parse json data in this? Please suggest me!!
I have do changes as per suggested!
What else i have to do here?
// Following is response from server shows inside Logcat
{"signup":[
{"sessionid":0,
"responsetype":"failure",
"message":"Username emailid already register."
}
]
}
// Following is my code
public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {
private EditText editTextfName;
private EditText editTextlName, editTextDid, editTextBd;
private EditText editTextPassword;
private EditText editTextEmail;
TextView txtBirthDate;
private Button buttonRegister;
Button buttonBdate;
String selected_date="";
int mYear, mMonth, mDay;
Calendar myCalendar;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
editTextfName = (EditText) findViewById(R.id.editTextfName);
editTextlName = (EditText) findViewById(R.id.editTextlName);
// editTextDid = (EditText) findViewById(R.id.editTextdid);
editTextBd = (EditText) findViewById(R.id.editTextbdate);
// txtBirthDate = (TextView) findViewById(R.id.txtBdate);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
buttonRegister = (Button) findViewById(R.id.buttonRegister);
buttonRegister.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.buttonRegister){
// Get the values given in EditText fields
String firstname = editTextfName.getText().toString();
String lastname = null;
String emailaddress = editTextEmail.getText().toString();
String birthdate = null;
String password = editTextPassword.getText().toString();
String deviceid = null;
System.out.println("Givennames is :" + firstname + " Given password is :" + password);
// Pass those values to connectWithHttpGet() method
connectWithHttpGet(firstname,lastname,emailaddress,birthdate,password,deviceid);
}
}
private void connectWithHttpGet(String firstname, String lastname, String emailaddress, String birthdate, String password, String deviceid) {
// Connect with a server is a time consuming process.
//Therefore we use AsyncTask to handle it
// From the three generic types;
//First type relate with the argument send in execute()
//Second type relate with onProgressUpdate method which I haven't use in this code
//Third type relate with the return type of the doInBackground method, which also the input type of the onPostExecute method
class HttpGetAsyncTask extends AsyncTask<String, Void, String> {
private Context context;
private HttpGetAsyncTask(Context context){
this.context=context;
}
#Override
protected String doInBackground(String... params) {
// As you can see, doInBackground has taken an Array of Strings as the argument
//We need to specifically get the givenUsername and givenPassword
String paramFname = params[0];
String paramLname = params[1];
String paramEmail = params[2];
String paramBirthdate = params[3];
String paramPassword = params[4];
String paramDeviceid = params[5];
System.out.println("userID" + paramFname + " password is :" + paramPassword);
// Create an intermediate to connect with the Internet
HttpClient httpClient = new DefaultHttpClient();
// Sending a GET request to the web page that we want
// Because of we are sending a GET request, we have to pass the values through the URL
HttpGet httpGet = new HttpGet("http://www.example.com/ypAndroid/api/signUp?firstname="+paramFname+"&lastname="+paramLname+"&emailid="+paramEmail+"&birthdate="+paramBirthdate+"&password="+paramPassword+"&deviceid="+null);
try {
// execute(); executes a request using the default context.
// Then we assign the execution result to HttpResponse
HttpResponse httpResponse = httpClient.execute(httpGet);
System.out.println("httpResponse// getEntity() ; obtains the message entity of this response");
// getContent() ; creates a new InputStream object of the entity.
// Now we need a readable source to read the byte stream that comes as the httpResponse
InputStream inputStream = httpResponse.getEntity().getContent();
// We have a byte stream. Next step is to convert it to a Character stream
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
// Then we have to wraps the existing reader (InputStreamReader) and buffer the input
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
// InputStreamReader contains a buffer of bytes read from the source stream and converts these into characters as needed.
//The buffer size is 8K
//Therefore we need a mechanism to append the separately coming chunks in to one String element
// We have to use a class that can handle modifiable sequence of characters for use in creating String
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
// There may be so many buffered chunks. We have to go through each and every chunk of characters
//and assign a each chunk to bufferedStrChunk String variable
//and append that value one by one to the stringBuilder
while((bufferedStrChunk = bufferedReader.readLine()) != null){
stringBuilder.append(bufferedStrChunk);
}
// Now we have the whole response as a String value.
//We return that value then the onPostExecute() can handle the content
System.out.println("Returninge of doInBackground :" + stringBuilder.toString());
// If the Username and Password match, it will return "working" as response
// If the Username or Password wrong, it will return "invalid" as response
return stringBuilder.toString();
} catch (ClientProtocolException cpe) {
System.out.println("Exceptionrates caz of httpResponse :" + cpe);
cpe.printStackTrace();
} catch (IOException ioe) {
System.out.println("Secondption generates caz of httpResponse :" + ioe);
ioe.printStackTrace();
}
return null;
}
// Argument comes for this method according to the return type of the doInBackground() and
//it is the third generic type of the AsyncTask
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
System.out.println("Post result :" + result);
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray login = jsonObject.getJSONArray("signup");
JSONObject jsonObject1 = login.getJSONObject(0);
String sessionid = jsonObject1.getString("sessionid");
String responsetype = jsonObject1.getString("responsetype");
String message = jsonObject1.getString("message");
Log.i("response",responsetype);
// Toast.makeText(RegisterActivity.this, responsetype, Toast.LENGTH_LONG).show();
if (TextUtils.equals(responsetype, "success")) {
Toast.makeText(RegisterActivity.this, "success !!" , Toast.LENGTH_LONG).show();
} else if (TextUtils.equals(responsetype, "failure")) {
Toast.makeText(RegisterActivity.this, "failed......!!", Toast.LENGTH_LONG).show();
}else {
Toast.makeText(RegisterActivity.this, "Invalid...", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
// Initialize the AsyncTask class
HttpGetAsyncTask httpGetAsyncTask = new HttpGetAsyncTask(RegisterActivity.this);
// Parameter we pass in the execute() method is relate to the first generic type of the AsyncTask
// We are passing the connectWithHttpGet() method arguments to that
httpGetAsyncTask.execute(firstname,lastname,emailaddress,birthdate,password,deviceid);
}
}
Your json has a key called responsetype
whereas you are using responsetypes in your code
String responsetypes = jsonObject1.getString("responsetypes");
remove the "s" and it should work.
String responsetypes = jsonObject1.getString("responsetype");
Also update your HttpGetAsyncTask class with below parameter and constructor. So add below code in your HttpGetAsyncTask
private Context context;
//in constructor:
public HttpGetAsyncTask(Context context){
this.context=context;
}
Then to initialize this calls use code as below -
HttpGetAsyncTask httpGetAsyncTask = new HttpGetAsyncTask(RegisterActivity.this);
instead of -
HttpGetAsyncTask httpGetAsyncTask = new HttpGetAsyncTask();
and to show toast use -
if (TextUtils.equals(responsetypes, "success")) {
Toast.makeText(context, "HTTP GET is working...", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Invalid...", Toast.LENGTH_LONG).show();
}
This is because AsyncTask doesn't inherit context and hence UI elements cannot be called using getApplicationContext() in AsyncTask
add an "s" to responsetype because in your json
{"signup":[
{"sessionid":0,
"responsetype":"failure",
"message":"Username emailid already register."
}
]
}
What is the Scenario
I want to send multiple ArrayList (usally 5) from android to the server and want to insert it into mysql database.
What I Have Done Successfully
I have Successfully send single value and Multiple Values from Android to PHP script using JSON
i have Received single and Multiple Records from mysql database to android using JSON
Here is the Code for inserting and getting value from server
class TeacherLogin1 extends AsyncTask<Void, Void, Void> {
String name,pass;
Context contextt;
int idofteach = 0;
int codee = 0;
TeacherLogin1(String pass1,String name1,Context context)
{
name = name1;
pass = pass1;
contextt = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
codee = Authenticate(name,pass);
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if(codee!=0)
{
Intent teachers = new Intent(context,TeachersView.class);
teachers.putExtra("TID", codee);
teachers.putExtra("TNAME", TeachName);
teachers.putExtra("sub1", subj1);
teachers.putExtra("sub2", subj2);
teachers.putExtra("sub3", subj3);
teachers.putExtra("sub4", subj4);
startActivity(teachers);
}
else
Toast.makeText(context, "Wrong Details", Toast.LENGTH_SHORT).show();
codee = 0;
}
}
public int Authenticate(String name,String Pass)
{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
// put the values of id and name in that variable
nameValuePairs.add(new BasicNameValuePair("name",name));
nameValuePairs.add(new BasicNameValuePair("pass",Pass));
try
{
HttpClient httpclient = new DefaultHttpClient();
ScriptsFilePath a = new ScriptsFilePath();
HttpPost httppost = new HttpPost(a.TeacherAuthen);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 1", e.toString());
}
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 2", e.toString());
}
try {
JSONObject jsonResponse = new JSONObject(result);
if(jsonResponse != null)
{
JSONArray jsonMainNode = jsonResponse.optJSONArray("GetTeacher");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
code = jsonChildNode.optInt("ID");
TeachName= jsonChildNode.optString("Name");
subj1= jsonChildNode.optString("subject1");
subj2= jsonChildNode.optString("subject2");
subj3= jsonChildNode.optString("subject3");
subj4= jsonChildNode.optString("subject4");
}
}
} catch (JSONException e) {
// Toast.makeText(getApplicationContext(), "Error" + e.toString(),
// Toast.LENGTH_SHORT).show();
}
return code;
}
and the TeacherAuthen.php script
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
$host="localhost";
$uname="root";
$pwd='';
$db="examsystem";
$con = mysql_connect($host,$uname,$pwd) or die("connection failed");
mysql_select_db($db,$con) or die("db selection failed");
if(isset($_REQUEST)){
$name=$_REQUEST['name'];
$pass=$_REQUEST['pass'];}
$flag['code']=0;
$name1['code1'] = "sdf";
$sql = "SELECT * FROM teachers WHERE Username ='$name' and Pass='$pass'";
$result = mysql_query($sql);
$json = array();
if(mysql_num_rows($result)){
while($row=mysql_fetch_assoc($result)){
$json['GetTeacher'][]=$row;
}
}
echo json_encode($json);
mysql_close($con);
?>
where i am stuck
I dont no how to send ArrayList from android to PHP Script.
For Example I want to send these arraylists to php script =
ArrayList<String> Questions= new ArrayList<String>();
ArrayList<String> A1= new ArrayList<String>();
ArrayList<String> A2= new ArrayList<String>();
ArrayList<String> A3= new ArrayList<String>();
ArrayList<String> A4= new ArrayList<String>();
and then in the PHP script i want to insert like this
"INSERT INTO `Question` (`ID` ,`Question` ,`A1` ,`A2` ,`A3` , `A4` ) VALUES (NULL, '$Question', '$A1', '$A2', '$A3' ,'$A4'); "
if i am able to send even a single arrayList then i think i can make a way to do the above
and Thanks for you Time
This is your Array: you can create more as required in your example.
ArrayList<String> contact = new ArrayList<String>();
Then, create a JSONcontacts variable of type JSONObject to store this array in this object
JSONObject JSONcontacts = new JSONObject();
Now, loop through all elements in that contact array and store it in the JSONcontacts
//Loop through array of contacts and put them to a JSONcontact object
for (int i = 0; i < contact.size(); i++) {
try {
JSONcontacts.put("Count:" + String.valueOf(i + 1), contact.get(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
Lets say you created many Arrays, which you probably have done, now you hvave to put them all into 1 JSON. So create a EverythingJSON variable of type JSONObject()
JSONObject EverythingJSON = new JSONObject();
and now put all your contact array and other arrays into it, right you loop through them as described above:
EverythingJSON.put("contact", JSONcontacts);
EverythingJSON.put("something", JSONsoemthing);
EverythingJSON.put("else", JSONelse);
now this is your AsynchTask to send them to your PHP server:
new AsyncTask() {
//String responseBody = "";
#SuppressWarnings("unused")
protected void onPostExecute(String msg) {
//Not Needed
}
protected Object doInBackground(Object... params) {
//Create Array of Post Variabels
ArrayList<NameValuePair> postVars = new ArrayList<NameValuePair>();
//Add a 1st Post Value called JSON with String value of JSON inside
//This is first and last post value sent because server side will decode the JSON and get other vars from it.
postVars.add(new BasicNameValuePair("JSON", EverythingJSON.toString());
//Declare and Initialize Http Clients and Http Posts
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Config.OnlineAPI);
//Format it to be sent
try {
httppost.setEntity(new UrlEncodedFormEntity(postVars));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
/* Send request and Get the Response Back */
try {
HttpResponse response = httpclient.execute(httppost);
String responseBody = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.v("MAD", "Error sending... ");
} catch (IOException e) {
e.printStackTrace();
Log.v("MAD", "Error sending... ");
}
return null;
}
}.execute(null, null, null);
Now on the PHP server side, you can loop through this JSON as such:
FIrst of all, get that JSON from POST and store it in a var:
//Receive JSON
$JSON_Received = $_POST["JSON"];
Now decode it from JSON:
//Decode Json
$obj = json_decode($JSON_Received, true);
And this is the loop to go through the array of contacts and get he Key and Value from it:
foreach ($obj['contact'] as $key => $value)
{
//echo "<br>------" . $key . " => " . $value;
}
you can repeat this loop for other Arrays you have sent :) Good Luck!
You cant send Arraylist to server,its an object. The best way to solve your problem is
user JSON , you need to do something like that -
ArrayList<String> Questions= new ArrayList<String>();
ArrayList<String> A1= new ArrayList<String>();
ArrayList<String> A2= new ArrayList<String>();
ArrayList<String> A3= new ArrayList<String>();
ArrayList<String> A4= new ArrayList<String>();
JsonArray jArr1= new JsonArray();
for(String data:A1)
{
jArr1.add(data);
}
JsonArray jArr2= new JsonArray();
for(String data:A2)
{
jArr2.add(data);
}
//convert each array list to jsonarray
JsonArray jArraySet = new JsonArray();
jArraySet.add(jArr1);
jArraySet.add(jArr2);
//add each json array to jArraySet
// then send the data via
HttpClient httpclient = new DefaultHttpClient();
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
// put the values of id and name in that variable
nameValuePairs.add(new BasicNameValuePair("all_arraylist",jArraySet.toString()));
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
note: dont forget to do it in asynctask
in php section ,do the following
<?php
$all_arraylist = $_POST['all_arraylist'];
$all_arraylist= json_decode($all_arraylist,TRUE); //this will give you an decoded array
print_r($all_arraylist); // display the array
// after seeing the array , i hope you will understand how to process it.
?>
Very simple. you should parse your JSON in php and get array of objects that you have sent. Here is solution
$JSON_Received = $_POST["json"];
$obj = json_decode($JSON_Received, true);
$array_1st_name = $obj[0];
$array_2nd_name = $obj[1];
and so on you will get all array of object.
I'm trying to send data to the server but it seems that I always send null values, any idea? The idea is to add a new customer through the mobile application to my database hosted in a server.
Here's my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nuevo_insert);
//etResponse = (EditText) findViewById(R.id.etResponse2);
etNombre = (EditText) findViewById(R.id.etNombre);
etApellido = (EditText) findViewById(R.id.etApellido);
etEdad = (EditText) findViewById(R.id.etEdad);
nombre = etNombre.getText().toString();
apellido = etApellido.getText().toString();
edad = etEdad.getText().toString();
}
public void insertar(View view) {
// Call AsyncTask to perform network operation on separate thread
// working in localhost you CAN'T put localhost in that address, you
// MUST put your IP address or it will crush
new HttpAsyncTask().execute("http://192.168.1.34/android/insertCustomer.php");
}
public static String GET(String url) {
InputStream inputStream = null;
String result = "";
try {
// create HttpClient
HttpClient httpClient = new DefaultHttpClient();
// make GET request to the given URL
HttpResponse httpResponse = httpClient.execute(new HttpGet(url+ "?nombre=" + nombre + "&apellido=" + apellido + "&edad="+ edad));
// receive response as InputStream
inputStream = httpResponse.getEntity().getContent();
// convert InputStream to string
if (inputStream != null) {
result = convertInputStreamToString(inputStream);
} else {
result = "No ha funcionat!";
}
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
return GET(urls[0]);
}
// onPostExecute displays the results of the AsyncTask
#Override
protected void onPostExecute(String result) {
String s = "";
Toast.makeText(getBaseContext(),getResources().getString(R.string.rebut), Toast.LENGTH_LONG).show();
JSONArray jArray;
try {
jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json = jArray.getJSONObject(i);
s = s + "Nom: " + json.getString("FirsName") + " "
+ json.getString("LastName") + "\n" + "Edat: "+ json.getInt("Age") + "\n\n";
}
etResponse.setText(s);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
This is my php file:
<?php
$con = mysql_connect('localhost', 'root', '');
if(!$con){
die("No se ha podido realizar la conexion: ".mysql_error());
}
mysql_select_db("TestDatabase", $con);
$nombre = $_GET['nombre'];
$apellido = $_GET['apellido'];
$edad = $_GET['edad'];
print_r($nombre."-".$apellido."-".$edad);
$result = mysql_query("insert into customer(FirsName, LastName, Age) values ('$nombre', '$apellido', '$edad')");
mysql_close($con);
?>
OK the problem was that I was retrieving the data from EditText boxes in the onCreate and I had to do it in the GET method :-)
If you are getting null value means that mean u r passing wrong type parameters or url may be wrong you do check it out
Change
HttpResponse httpResponse = httpClient.execute(new HttpGet(url+ "?nombre=" + nombre + "&apellido=" + apellido + "&edad="+ edad));
to this:
String request = url+ "?nombre=" + nombre + "&apellido=" + apellido + "&edad="+ edad;
Log.d("DEBUG", request);
HttpResponse httpResponse = httpClient.execute(request);
and see your logcat for your url, maybe it is broken.
if the url is ok, then try opening this url in your browser and check the results.
I'm trying to get all value from a JSON API, I've managed to get almost all of them, except one! As you can see, this is the JSON output from the server. (I can't change it)
{
"error":"",
"S8tf":{
"infoToken":"wCfhXe",
"deleteToken":"gzHTfGcF",
"size":122484,
"sha1":"8c4e2bbc0794d2bd4f901a36627e555c068a94e6",
"filename":"Screen_Shot_2013-07-02_at_3.52.23_PM.png"
},
"S29N":{
"infoToken":"joRm6p",
"deleteToken":"IL5STLhq",
"size":129332,
"sha1":"b4a03897121d0320b82059c36f7a10a8ef4c113d",
"filename":"Stockholmsyndromet.docx"
}
}
As you can see, each string/"array" begins with a "fileId" this is randomly generated from the server. I'm using the code below, I can see all values like: filename, size, sh1 etc. But I can't seem to figure out how to get the "fileId". The fileId is (in this json) S8tf and S29N
My code:
public class FilesActivity extends SherlockActivity {
private static String TAG_FILENAME = "filename";
private static String TAG_SIZE = "size";
private static String TAG_ITOKEN = "infoToken";
private static String TAG_DTOKEN = "deleteToken";
private static String TAG_SHA1 = "sha1";
private ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dblist);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Files");
String response = null;
DefaultHttpClient httpClient = new DefaultHttpClient();
ResponseHandler <String> resonseHandler = new BasicResponseHandler();
HttpPost postMethod = new HttpPost("http://api.bayfiles.net/v1/account/files?session=of1903u3pj43c3can8rc33gc42");
try {
JSONObject json = new JSONObject();
json.put("filename", "error");
postMethod.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
postMethod.setHeader( "Content-Type", "application/json" );
response = httpClient.execute(postMethod,resonseHandler);
TextView txt = (TextView)findViewById(R.id.nodata);
JSONObject request = new JSONObject(response);
for (Iterator<?> keyIterator = request.keys(); keyIterator.hasNext(); ) {
String key = (String) keyIterator.next();
JSONObject object = request.optJSONObject(key);
ArrayList<fileObject> objectList = new ArrayList<fileObject>();
if (object != null) {
//Setting TAGs
TAG_FILENAME = object.getString("filename");
TAG_SIZE = object.getString("size");
TAG_ITOKEN = object.getString("infoToken");
TAG_DTOKEN = object.getString("deleteToken");
TAG_SHA1 = object.getString("sha1");
txt.setText(
TAG_FILENAME + "\n"
+ TAG_SIZE + "\n"
+ TAG_ITOKEN + "\n"
+ TAG_DTOKEN + "\n"
+ TAG_SHA1 + "\n"
+ txt.getText()
);
Log.d("log_tag", object.getString("filename"));
}
}
}
catch(Exception e)
{
e.printStackTrace();
Log.d("log_tag", "Error: " + e.toString());
}
}
}
If you didn't get it, I'm trying to catch the value from fileId aka S8tf and S29N, these are random numbers and produced by the server.
EDIT: Got it working thanks to you guys! Since I know it's irritating that the poster figure it out, and you can't, what I did is to put String fileId = key; Inside my object loop, like this:
if (object != null) {
fileObject obj = new fileObject();
obj.setFileId(key);
obj.setFileName(object.getString("filename"));
obj.setSize(object.getString("size"));
obj.setInfoToken(object.getString("infoToken"));
obj.setDeleteToken(object.getString("deleteToken"));
obj.setSha1(object.getString("sha1"));
objectList.add(obj);
Log.d("fileId", key); // Shows both of the values!
}
I just looked at the JSONObject documentation:
I feel like the getNames()-method could be what you are searching for.
If you take a look at the first part of your for loop...
JSONObject request = new JSONObject(response);
for (Iterator<?> keyIterator = request.keys(); keyIterator.hasNext(); ) {
String key = (String) keyIterator.next();
JSONObject object = request.optJSONObject(key);
You request all of the keys from the JSONObject that represents your response from the server. These keys are the values you are looking for. If you were to add a
System.out.println(key);
after the first line in your loop, you will see the values printed out ('error','S8tf', ...).
Background : I am trying to develop my first android application which is a student discussion panel. I am good with PHP and MySQL but don't have much experience in android Java.
Issue:
In SelectedQuestionActivity class, if I simply give the URL as http://thewbs.getfreehosting.co.uk/talky/fetchans.php?qid=3, it works just fine and it fetches the corresponding answer to the question.
But if I do it the way I have shown in the code below, the application crashes. I am not sure where I am wrong.
CODE:
AllQuestionActivity.java
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.qid)).getText()
.toString();
//pid is the value of the selected question for example www.example.com/fetchans?qid=3 so here pid value is supposed to be 3.
// Starting new intent
Intent in = new Intent(getApplicationContext(),
SelectedQuestionActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
startActivity(in);
}
});
Now in SelectedQuestionActivity.java
code:
public class SelectedQuestionActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
Intent intent = getIntent();
String qid = intent.getExtras().getString(TAG_PID);
// url to get all products list
private String url_all_products = "http://thewbs.getfreehosting.co.uk/talky/fetchans.php?qid="+qid;
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "ques";
private static final String TAG_PID = "aid";
private static final String TAG_NAME = "aname";
private static final String TAG_INFO = "answer";
private static final String TAG_DATE = "date";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_ans);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
}
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SelectedQuestionActivity.this);
pDialog.setMessage("Loading Answers. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Answers: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
String info = c.getString(TAG_INFO);
String date = c.getString(TAG_DATE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
map.put(TAG_INFO, info);
map.put(TAG_DATE, date);
// adding HashList to ArrayList
productsList.add(map);
}
}
else {
}
} 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(
SelectedQuestionActivity.this, productsList,
R.layout.list_selected_ques, new String[] { TAG_PID,
TAG_NAME, TAG_INFO, TAG_DATE },
new int[] { R.id.aid, R.id.aname, R.id.answer, R.id.date});
// updating listview
setListAdapter(adapter);
}
});
}
}
}
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;
}
}
Currently you are trying to getIntent outside onCreate of ListActivity so move it inside onCreate method as :
Intent intent;
String qid;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_ans);
// get Intent here
intent = getIntent();
qid = intent.getExtras().getString(TAG_PID);
// your code here
and also no need to use runOnUiThread method for updating UI from onPostExecute because onPostExecute method called on Ui thread we can access UI elements in it
EDIT:-
you are not adding any paramter to NameValuePair inside doInBackground . add quid before sending it to makeHttpRequest as :
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
add quid param here
params.add(new BasicNameValuePair("qid",qid)); //<<<< add here
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(
url_all_products,
"GET",
params);
// your code here
You are passing a string from one activity object to another , while you didn't write code to receive it on the new activity in the right place.
To solve this you should add some code to your onCreate:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_ans);
String url = getIntent().getStringExtra(TAG_PID);
if (url != null)
url_all_products = url;
You should need to get your intent values in onCreate() as below :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_ans);
Intent intent = getIntent();
String qid = intent.getExtras().getString(TAG_PID);
}