I would like to select text from a textview,partially that is for Gingerbread as well as higher platforms,I find that android:textIsSelectable is not available and the WebView workaround only does it for complete text,I have tried to use pre-baked code to do this by extending a TextView:
public class SelectableTextView extends TextView {
final String TAG="SelectableTextView";
public static int _SelectedBackgroundColor = 0xffA6D4E1;
public static int _SelectedTextColor = 0xff000000;
private OnTouchListener lastOnTouch;
protected int textOffsetStart;
protected int textOffsetEnd;
private OnLongClickListener lastOnLongClick;
protected boolean longCliked;
protected boolean isDowned;
protected int textSelectedEnd;
protected int textSelectedStart;
private static SelectableTextView lastInstance;
public SelectableTextView(Context context) {
super(context);
}
public SelectableTextView(Context context,AttributeSet attrs)
{
super(context,attrs);
}
public SelectableTextView(Context context,AttributeSet attrs,int defStyle)
{
super(context,attrs,defStyle);
}
@SuppressLint("NewApi")
public void setTextIsSelectable(boolean selectable) {
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB)
super.setTextIsSelectable(true);
else
{
super.setLongClickable(true);
super.setOnLongClickListener(getSelectableLongClick());
super.setOnTouchListener(getSelectableOnTouch());
}
}
private OnLongClickListener getSelectableLongClick() {
return new OnLongClickListener() {
@override
public boolean onLongClick(View v) {
longCliked = true;
if (lastOnLongClick != null) {
lastOnLongClick.onLongClick(v);
}
return true;
}
};
}
@override
public void setOnTouchListener(OnTouchListener listener) {
super.setOnTouchListener(listener);
this.lastOnTouch = listener;
}
@override
public void setOnLongClickListener(OnLongClickListener listener) {
super.setOnLongClickListener(listener);
Log.d(TAG, "Setting touch listener in long click");
this.lastOnLongClick = listener;
// this.setOnTouchListener(getSelectableOnTouch());
}
private OnTouchListener getSelectableOnTouch() {
return new OnTouchListener() {
@override
public boolean onTouch(View v, MotionEvent event) {
Log.d(TAG, "In SelectableTextView OnTouchListener");
int action = event.getAction();
if (action == MotionEvent.ACTION_DOWN) {
Log.d(TAG, "Finger down on the TextView");
if (lastInstance == null)
lastInstance = SelectableTextView.this;
if (lastInstance != null && lastInstance != SelectableTextView.this) {
lastInstance.clean();
lastInstance = SelectableTextView.this;
}
int offset = getOffset(event);
Log.d(TAG, "Selection starts at: "+offset);
if ((offset < textOffsetEnd && offset > textOffsetStart)
|| (offset > textOffsetEnd && offset < textOffsetStart)) {
if (textOffsetEnd - offset > offset - textOffsetStart)
textOffsetStart = textOffsetEnd;
} else {
clean();
textOffsetStart = offset;
}
isDowned = true;
} else if (isDowned && longCliked && action == MotionEvent.ACTION_MOVE) {
Log.d(TAG, "Selecting text");
selectTextOnMove(event);
} else if (action == MotionEvent.ACTION_UP) {
isDowned = false;
longCliked = false;
}
if (lastOnTouch != null)
lastOnTouch.onTouch(v, event);
return false;
}
};
}
private void selectTextOnMove(MotionEvent event) {
Log.d(TAG, "Selection text on ACTION_MOVE");
int offset = getOffset(event);
if (offset != Integer.MIN_VALUE) {
String text = getText().toString();
SpannableStringBuilder sb = new SpannableStringBuilder(text);
BackgroundColorSpan bgc = new BackgroundColorSpan(_SelectedBackgroundColor);
ForegroundColorSpan textColor = new ForegroundColorSpan(_SelectedTextColor);
int start = textOffsetStart;
textOffsetEnd = offset;
int end = offset;
Log.d(TAG,"Start: "+start+"and End: "+end);
if (start > end) {
int temp = start;
start = end;
end = temp;
Log.d(TAG, "Interchanging Start: "+start+" and End: "+end);
}
int[] curectStartEnd = curectStartEnd(text, start, end);
start = curectStartEnd[0];
end = curectStartEnd[1];
Log.d(TAG, "Corrected start and end,Start: "+start+" and End: "+end+".These values are final");
SelectableTextView.this.textSelectedStart = start;
SelectableTextView.this.textSelectedEnd = end;
sb.setSpan(bgc, start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
sb.setSpan(textColor, start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
this.setText(sb);
}
}
private int[] curectStartEnd(String text, int start, int end) {
int length = text.length();
while (start < length && start > 0 && text.charAt(start) != ' ') {
start--;
}
while (end < length && text.charAt(end) != ' ') {
end++;
}
return new int[] { start, end };
}
private int getOffset(MotionEvent event) {
Log.d(TAG,"Get offset method");
Layout layout = getLayout();
if (layout == null)
return Integer.MIN_VALUE;
float x = event.getX() + getScrollX();
float y = event.getY() + getScrollY();
int line = layout.getLineForVertical((int) y);
Log.d(TAG, "Obtaining line "+line);
int offset = layout.getOffsetForHorizontal(line, x);
return offset;
}
protected void clean() {
String gotText=this.getText().toString();
if (gotText != null) {
this.setText(gotText);
textSelectedStart = 0;
textSelectedEnd = 0;
}
}
@override
public int getSelectionStart() {
return textSelectedStart;
}
@override
public int getSelectionEnd() {
return textSelectedEnd;
}
}
This is how I am using it:
txt_copyFrom.setClickable(false);
txt_copyFrom.setCursorVisible(true);
txt_copyFrom.setEnabled(true);
txt_copyFrom.setTextIsSelectable(true);
txt_copyFrom.setOnLongClickListener(new OnLongClickListener(){
@override
public boolean onLongClick(View v) {
Log.d(TAG, "On LongClick Listener");
int start=txt_copyFrom.getSelectionStart();
int end=txt_copyFrom.getSelectionEnd();
if(start>end)
{
//I guess the SelectableTextView fixes this:
start=start+end;
end=start=end;
start=start-end;
}
mSelectedText=txt_copyFrom.getText().toString().substring(start, end);
Log.d(TAG, "Selected text: "+mSelectedText);
return true;
}});
I get a StackOverflowError:
It repeatedly prints the message:
SelectableTextView(12712): In SelectableTextView OnTouchListener
SelectableTextView(12712): Finger down on the TextView
SelectableTextView(12712): Get offset method
SelectableTextView(12712): Obtaining line 4
SelectableTextView(12712): Selection starts at: 205
Followed by:
AndroidRuntime(12712): FATAL EXCEPTION: main
AndroidRuntime(12712): java.lang.StackOverflowError
AndroidRuntime(12712): at android.text.MeasuredText.addStyleRun(MeasuredText.java:164)
AndroidRuntime(12712): at android.text.MeasuredText.addStyleRun(MeasuredText.java:204)
at android.text.StaticLayout.generate(StaticLayout.java:281)
AndroidRuntime(12712): at android.text.DynamicLayout.reflow(DynamicLayout.java:284)
AndroidRuntime(12712): at android.text.DynamicLayout.<init>(DynamicLayout.java:170)
AndroidRuntime(12712): at android.widget.TextView.makeSingleLayout(TextView.java:6044)
AndroidRuntime(12712): at android.widget.TextView.makeNewLayout(TextView.java:5942)
AndroidRuntime(12712): at android.widget.TextView.checkForRelayout(TextView.java:6481)
AndroidRuntime(12712): at android.widget.TextView.setText(TextView.java:3764)
AndroidRuntime(12712): at android.widget.TextView.setText(TextView.java:3622)
AndroidRuntime(12712): at android.widget.TextView.setText(TextView.java:3597)
AndroidRuntime(12712): at com.example.clipboardtest.SelectableTextView.clean(SelectableTextView.java:185)
This happens to be:this.setText(this.getText().toString());
This is followed by:
AndroidRuntime(12712): at com.example.clipboardtest.SelectableTextView$2.onTouch(SelectableTextView.java:108)
This is,as expected: clean();
Then this occurs repeatedly:
AndroidRuntime(12712): at com.example.clipboardtest.SelectableTextView$2.onTouch(SelectableTextView.java:120)
which is `lastOnTouch.onTouch(v, event);`
I guess this is because we retain the OnLongClick and OnTouchListener.
Also the code calls for selection of stuff using a background colour and foreground color:
SpannableStringBuilder sb = new SpannableStringBuilder(text);
BackgroundColorSpan bgc = new BackgroundColorSpan(_SelectedBackgroundColor);
ForegroundColorSpan textColor = new ForegroundColorSpan(_SelectedTextColor);
sb.setSpan(bgc, start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
sb.setSpan(textColor, start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
setText(this);
I do not understand why this implementation does not chain to the superclass implementation like I specifically asked it to.Is there anything else I can do,any approach I can follow to make it work,is there a pre-implemented version I can use.If there is nothing can you guide me through implementing a custom TextView for Android
I'm trying to get the result of the asynctask by using an interface but when I've tried to use the methods on that interface my app keeps on crashing.
This project has 4 java files: MainActivity.java , SigninActivity.java , GetAvailableExam.java , AsyncResponse.java
I'm pretty sure the error is not on the GetAvailableExam.java because it is just an activity that prints hello world so I'm not going to post it's code here.
MainActivity.java
Code:
package com.it4.anexsysclient;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements AsyncResponse {
private EditText usernameField,passwordField;
private TextView status,role,method;
SigninActivity signinactivity = new SigninActivity();
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
usernameField = (EditText)findViewById(R.id.editText1);
passwordField = (EditText)findViewById(R.id.editText2);
status = (TextView)findViewById(R.id.textView6);
role = (TextView)findViewById(R.id.textView7);
method = (TextView)findViewById(R.id.textView9);
signinactivity.delegate = this;
}
[user=439709]@override[/user]
public boolean onCreateOptionsMenu(Menu menu) {
usernameField.setText("stud");
passwordField.setText("stud");
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void login(View view){
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
method.setText("Get Method");
new SigninActivity(this,status,role,0).execute(username,password);
}
public void loginPost(View view){
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
method.setText("Post Method");
new SigninActivity(this,status,role,1).execute(username,password);
}
public void processFinish(String output){
//Toast.makeText(getApplicationContext(), output, Toast.LENGTH_LONG).show();
}
}
SigninActivity.java
Code:
package com.it4.anexsysclient;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.TextView;
public class SigninActivity extends AsyncTask<String,Void,String>{
private TextView statusField,roleField;
private Context context;
private int byGetOrPost = 0;
private String server_ip;
private ProgressDialog progress;
public AsyncResponse delegate=null;
public SigninActivity() {
}
//flag 0 means get and 1 means post.(By default it is get.)
public SigninActivity(Context context,TextView statusField,
TextView roleField,int flag) {
this.context = context;
this.statusField = statusField;
this.roleField = roleField;
byGetOrPost = flag;
this.progress = new ProgressDialog(context);
}
protected void onPreExecute(){
server_ip = "http://192.168.0.101/anexsys/examination-manager.php";
this.progress.setMessage("Logging in");
this.progress.show();
}
[user=439709]@override[/user]
protected String doInBackground(String... arg0) {
if(byGetOrPost == 0){ //means by Get Method
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link = "http://myphpmysqlweb.hostei.com/login.php?username="
+username+"&password="+password;
URL url = new URL(link);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(link));
HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line="";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
}catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
else{
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link=server_ip;
String data = URLEncoder.encode("username", "UTF-8")
+ "=" + URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8")
+ "=" + URLEncoder.encode(password, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter
(conn.getOutputStream());
wr.write( data );
wr.flush();
BufferedReader reader = new BufferedReader
(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
return sb.toString();
}catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
}
[user=439709]@override[/user]
protected void onPostExecute(String result){
this.statusField.setText("Login Successful");
this.roleField.setText(result);
this.progress.dismiss();
delegate.processFinish(result);
//Log.d("ADebugTag", "Value: " + result);
//if(result.toString()=="student") {
//context.startActivity(new Intent(context, GetAvailableExam.class));
//}
}
}
AsyncResponse.java
Code:
package com.it4.anexsysclient;
public interface AsyncResponse {
void processFinish(String output);
}
Code:
protected void onPostExecute(String result){
this.statusField.setText("Login Successful");
this.roleField.setText(result);
this.progress.dismiss();
delegate.processFinish(result);
//Log.d("ADebugTag", "Value: " + result);
//if(result.toString()=="student") {
//context.startActivity(new Intent(context, GetAvailableExam.class));
//}
}
The delegate.processFinish(result) is the one causing the crash, The app works fine if I try to remove/comment out it.
Would be helpfull with some more information, for instance: what exception is it you get?
My guess is a nullpointer? Which by a quick glance i'd suspect is that you never set "delegate" in your signinactivity.
You create signinactivity during creation of mainactivity.
Code:
[B]SigninActivity signinactivity = new SigninActivity();[/B]
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
usernameField = (EditText)findViewById(R.id.editText1);
passwordField = (EditText)findViewById(R.id.editText2);
status = (TextView)findViewById(R.id.textView6);
role = (TextView)findViewById(R.id.textView7);
method = (TextView)findViewById(R.id.textView9);
[B]signinactivity.delegate = this;[/B]
}
However that instance is later never used from what i can tell? You create new instances later in code when its used, where delegate won't be set.
Code:
public void login(View view){
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
method.setText("Get Method");
[B]new SigninActivity(this,status,role,0).execute(username,password);[/B]
}
public void loginPost(View view){
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
method.setText("Post Method");
[B] new SigninActivity(this,status,role,1).execute(username,password);[/B]
}
I am new to Java and I am getting kind of stuck by trying to loop through my JSON. I am retrieving a JSON object where I want to loop through.
My JSON looks as follow:
Code:
{"message":{"2":[{"uid":"2","title":"","message":"Test1","success":1,"created_at":null,"updated_at":null}],"3":[{"uid":"3","title":"","message":"Test2 !","success":1,"created_at":null,"updated_at":null}],"4":[{"uid":"4","title":"Bla","message":"Test3!","success":1,"created_at":null,"updated_at":null}]}}
I tried a loop like this:
Code:
for(int i = 0; i<json.names().length(); i++){
try {
Log.v("TEST", "key = " + json.names().getString(i) + " value = " + json.get(json.names().getString(i)));
} catch (JSONException e) {
e.printStackTrace();
}
}
But this will only target "message" which includes the whole JSON "string". I want to loop through each message and retrieving the value of uid 1, uid 2 etc. How can I achieve this?
Thanks in advance.
Here is how I'm doing it:
Code:
private static final String AllNewsItemsURL = "some_url_here.php";
private static final String TAG_SUCCESS = "success";
private static final String NEWS = "news";
private static final String TITLE = "title";
private static final String STORY = "story";
private final JSONParser jParser = new JSONParser();
private JSONArray newsItems = null;
..... / code snipped / ....
try {
JSONObject json = jParser.makeHttpRequest(AllNewsItemsURL, params);
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
newsItems = json.getJSONArray(NEWS);
for (int i = 0; i < newsItems.length(); i++) {
JSONObject obj = newsItems.getJSONObject(i);
Integer id = i + 1;
String title = obj.getString(TITLE);
String story = obj.getString(STORY);
}
} else {
Log.e("JSON Response", "success == 0");
}
} catch (Exception e) {
e.printStackTrace();
}
Thanks for your reply. I tried it but getting this exception:
Code:
org.json.JSONException: Value {"2":[{"uid":"2","title":"","message":"Test1","success":1,"created_at":null,"updated_at":null}],"3":[{"uid":"3","title":"","message":"Test2","success":1,"created_at":null,"updated_at":null}],"4":[{"uid":"4","title":"Bla","message":"Test3","success":1,"created_at":null,"updated_at":null}]} at messages of type org.json.JSONObject cannot be converted to JSONArray
CodeMonkeyy said:
Thanks for your reply. I tried it but getting this exception:
Code:
org.json.JSONException: Value {"2":[{"uid":"2","title":"","message":"Test1","success":1,"created_at":null,"updated_at":null}],"3":[{"uid":"3","title":"","message":"Test2","success":1,"created_at":null,"updated_at":null}],"4":[{"uid":"4","title":"Bla","message":"Test3","success":1,"created_at":null,"updated_at":null}]} at messages of type org.json.JSONObject cannot be converted to JSONArray
Click to expand...
Click to collapse
You might want to try the matching JSONParser I have for it, sorry forgot to include it:
https://github.com/JonnyXDA/WGSB/bl...om/jonny/wgsb/material/parser/JSONParser.java
Also noting that your entire JSON Array is called "message" but you also have a parameter called "message" - maybe rename the Array to "messages"?
As for the code you should have something like:
Code:
private static final String AllNewsItemsURL = "some_url_here.php";
private static final String TAG_SUCCESS = "success";
private static final String MESSAGES = "messages";
private static final String TITLE = "title";
private static final String MESSAGE = "message";
private final JSONParser jParser = new JSONParser();
private JSONArray messageItems = null;
..... / code snipped / ....
try {
JSONObject json = jParser.makeHttpRequest(AllNewsItemsURL, params);
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
messageItems = json.getJSONArray(MESSAGES);
for (int i = 0; i < messageItems.length(); i++) {
JSONObject obj = messageItems.getJSONObject(i);
String title = obj.getString(TITLE);
String message = obj.getString(MESSAGE);
}
} else {
Log.e("JSON Response", "success == 0");
}
} catch (Exception e) {
e.printStackTrace();
}
My code looks like the this:
Code:
//Message task
MessageTask task = new MessageTask(DashboardActivity.class);
task.execute();
try {
json = task.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
messageItems = json.getJSONArray(MESSAGES);
for (int i = 0; i < messageItems.length(); i++) {
JSONObject obj = messageItems.getJSONObject(i);
String title = obj.getString(TITLE);
String message = obj.getString(MESSAGE);
}
} else {
Log.e("JSON Response", "success == 0");
}
} catch (Exception e) {
e.printStackTrace();
}
I am using Async Task to retrieve my JSON.
And my JSON parser looks like this:
Code:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
// Making HTTP request
try {
// 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();
} 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();
Log.e("JSON", json);
} 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;
}
}
But it doesn't get through the if statement, because it can't find the value success. ( org.json.JSONException: No value for success ). Don't really know what I am doing wrong here. Is it because I am using AsyncTask and retrieving my JSON the wrong way?
I also renamed my Array to "messages", stupid mistake thanks!
CodeMonkeyy said:
But it doesn't get through the if statement, because it can't find the value success. ( org.json.JSONException: No value for success ). Don't really know what I am doing wrong here. Is it because I am using AsyncTask and retrieving my JSON the wrong way?
I also renamed my Array to "messages", stupid mistake thanks!
Click to expand...
Click to collapse
We're getting closer! With regards to using AsyncTask - thats fine and the recommended way to do service side sync/download operations (doesn't block the UI thread) so no need to change that.
I just took a look at my reference JSON and I have the success tag outside of an item eg:
Code:
{"topical":[{"tid":"5","title":"Exam countdown... just 12 weeks left!","story":"some_story_text_here","staff":"0","red":"0","show":"1"}],[COLOR="red"]"success":1[/COLOR]}
Whereas your success tag is put in each item:
Code:
{"message":{"2":[{"uid":"2","title":"","message":"Test1","[COLOR="red"]success":1,[/COLOR]"created_at":null,"updated_at":null}],"3":[{"uid":"3","title":"","message":"Test2 !",[COLOR="red"]"success":1[/COLOR],"created_at":null,"updated_at":null}],"4":[{"uid":"4","title":"Bla","message":"Test3!","[COLOR="Red"]success":1[/COLOR],"created_at":null,"updated_at":null}]}}
I'm guessing that your php line for:
PHP:
$response["success"] = 1;
is inside of the while loop:
PHP:
while ($row = mysql_fetch_array($result)) {
Taking it out of the while loop should fix that
That makes sense, because I am trying to get a success code for my whole JSON response. I changed my PHP code to:
Code:
while($row = mysqli_fetch_array( $messages )) {
// create rowArr
$rowArr = array(
'uid' => $row['id'],
'title' => $row['title'],
'message' => $row["message"],
'created_at' => $row['created_at'],
'updated_at' => $row['updated_at'],
);
// store rowArr in $return_arr
$return_arr[$row['id']][] = $rowArr;
}
$return_arr['success'] = 1;
// Json encode
echo json_encode(array("messages" => $return_arr));
}
Retrieving the following JSON:
Code:
{"messages":{"2":[{"uid":"2","title":"","message":"Test1","created_at":null,"updated_at":null}],"3":[{"uid":"3","title":"","message":"Test2 !","created_at":null,"updated_at":null}],"4":[{"uid":"4","title":"Bla","message":"Test3!","created_at":null,"updated_at":null}],"success":1}}
But I am still getting the following exception:
Code:
org.json.JSONException: No value for success
The success tag is still being encoded as part of an inner array, not the first array - try this:
PHP:
if (mysql_num_rows($messages) > 0) {
$response["messages"] = array();
while ($row = mysql_fetch_array($messages)) {
$messagesArray= array(
'uid' => $row['id'],
'title' => $row['title'],
'message' => $row['message'],
'created_at' => $row['created_at'],
'updated_at' => $row['updated_at'],
);
array_push($response["messages"], $messagesArray);
}
$response["success"] = 1;
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No messages found";
echo json_encode($response);
}
And it's finally working!
Getting the following JSON result:
Code:
{"tag":"message","success":1,"error":0,"messages":[{"uid":"2","title":"","message":"Test1","created_at":null,"updated_at":null},{"uid":"3","title":"","message":"Test2!","created_at":null,"updated_at":null},{"uid":"4","title":"Bla","message":"Test3!","created_at":null,"updated_at":null}]}
And I can successfully loop through my JSON with the following code:
Code:
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
messageItems = json.getJSONArray(MESSAGES);
for (int i = 0; i < messageItems.length(); i++) {
JSONObject obj = messageItems.getJSONObject(i);
String title = obj.getString(TITLE);
String message = obj.getString(MESSAGE);
Log.e("TITLE :", title);
Log.e("MESSAGE :", message);
}
} else {
Log.e("JSON Response", "success == 0");
}
} catch (Exception e) {
e.printStackTrace();
}
Thank you very much! So the problem was that I placed the "success" tag outside my Array?
( Volley > sending GET Request with parameters ) How to flatten Map<String,String> pa
I got this custom volley request class that extends Request with the request parameters in Map<String,String> format, my question is how to flatten Map<String,String> parameters correctly into a query string and receive it with PHP $_GET?
Code:
public class GsonGetRequest_Exp5<T> extends Request<T> {
private Response.Listener<T> listener;
private Map<String, String> params;
private Type type;
private Gson gson;
public GsonGetRequest_Exp5(String url, Map<String, String> params, Type type, Gson gson,
Response.Listener<T> reponseListener, Response.ErrorListener errorListener) {
super(Method.GET, url, errorListener);
this.type = type;
this.gson = gson;
this.listener = reponseListener;
this.params = params;
}
public GsonGetRequest_Exp5(int method, String url, Map<String, String> params, Type type, Gson gson,
Response.Listener<T> reponseListener, Response.ErrorListener errorListener) {
super(method, url, errorListener);
this.type = type;
this.gson = gson;
this.listener = reponseListener;
this.params = params;
}
@Override
protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
return params;
};
@Override
protected void deliverResponse(T response) {
listener.onResponse(response);
}
@Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return (Response<T>) Response.success
(
gson.fromJson(jsonString, type),
HttpHeaderParser.parseCacheHeaders(response)
);
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JsonSyntaxException je) {
return Response.error(new ParseError(je));
}
}
}
Code:
public static GsonGetRequest_Exp5<ArrayList<FeedObject>> gsonGetRequest_exp6
(
Response.Listener<ArrayList<FeedObject>> listener,
Response.ErrorListener errorListener,
String str
)
{
//final String url = "example.com/php.php";
final Map<String, String> params = new HashMap<String, String>();
final Gson gson = new GsonBuilder()
.registerTypeAdapter(FeedObject.class, new FeedObjectDeserializer())
.create();
String test_url = "example.com/php.php";
params.put("SearchKey", str);
StringBuilder builder = new StringBuilder();
for (String key : params.keySet())
{
Object value = params.get(key);
if (value != null)
{
try
{
value = URLEncoder.encode(String.valueOf(value), HTTP.UTF_8);
if (builder.length() > 0)
builder.append("&");
builder.append(key).append("=").append(value);
}
catch (UnsupportedEncodingException e)
{
}
}
}
test_url += "?" + builder.toString();
return new GsonGetRequest_Exp5
(
test_url,
params,
new TypeToken<ArrayList<FeedObject>>() {}.getType(),
gson,
listener,
errorListener
);
}
problem with my code is, the "params" I keep getting "null", nothing is added to the end of my example.com url, can anyone point out what I did wrong?