Android - My onPostExecute in AsyncTask is not getting called - java

So I have been trying to fetch JSON objects in my Django REST Framework API. The algorithm for this called within the onPostExecute of my AsyncTask but it seems that it is not being called as when I debug it doesn't go there. Nothing fatal seems to be appearing in my logcat except that there is nothing in my array that should contain data from the DRF API.
I have two activities that calls my AsyncTask from my WSAdapter class. One is for logging in and the other is for listing all posts once logged in.
The logging in works just fine but listing the posts doesn't.
My code is below:
Posts.java
public class Posts extends AppCompatActivity {
TextView postsSect;
Button postsDoneBtn;
WSAdapter.SendAPIRequests PostsHelper;
StringBuilder postsBuffer = new StringBuilder();
#Override
protected void onResume(){
super.onResume();
PostsDetails postDetailsHelper = new PostsDetails();
postDetailsHelper.ListPosts();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_posts);
PostsDetails postDetailsHelper = new PostsDetails();
postsDoneBtn = (Button) findViewById(R.id.PostsDoneButton);
postDetailsHelper.callPostDetails("192.168.0.18:8000/api");
postDetailsHelper.ListPosts();
postDetailsHelper.postDetailsCalled('n');
postsDoneBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Posts.this, MainActivity.class));
}
});
}
public class PostsDetails {
//String post_title, post_content;
ArrayList<Integer> post_id = new ArrayList<Integer>();
ArrayList<String> post_title = new ArrayList<String>();
ArrayList<String> post_content = new ArrayList<String>();
boolean isPDCalled;
// sets if Post details are called
boolean postDetailsCalled(char called) {
if (called == 'y'){
return true;
}
return false;
}
// checks if postsDetails functions are called for AsyncTask
boolean getIsPDCalled(){
return isPDCalled;
}
// calls the execute for AsyncTask
private void callPostDetails(String theurl){
PostsHelper = new WSAdapter.SendAPIRequests();
// sets if post details are called
postDetailsCalled('y');
// executes AsyncTask
PostsHelper.execute(theurl);
}
// sets values for the posts arrays
public void setPost(int p_id, String p_title, String p_content) {
post_id.add(p_id);
post_title.add(p_title);
post_content.add(p_content);
}
// Lists the posts from the database
public void ListPosts() {
/////////// add functionality if a post was deleted and was clicked
postsSect = (TextView) findViewById(R.id.PostsSection);
postsSect.setText(post_title.get(post_title.size()) + "\n");
for (int i = post_id.size() - 1; i > 0; i--)
{
postsSect.append(post_title.get(i));
}
}
}
}
WSAdapter.java
public class WSAdapter extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
static public class SendAPIRequests extends AsyncTask<String, String, String> {
// Add a pre-execute thing
#Override
protected String doInBackground(String... params) {
Log.e("TAG", params[0]);
Log.e("TAG", params[1]);
String data = "";
HttpURLConnection httpURLConnection = null;
try {
// Sets up connection to the URL (params[0] from .execute in "login")
httpURLConnection = (HttpURLConnection) new URL(params[0]).openConnection();
// Sets the request method for the URL
httpURLConnection.setRequestMethod("POST");
// Tells the URL that I am sending a POST request body
httpURLConnection.setDoOutput(true);
// To write primitive Java data types to an output stream in a portable way
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
// Writes out a byte to the underlying output stream of the data posted from .execute function
wr.writeBytes("postData=" + params[1]);
// Flushes the postData to the output stream
wr.flush();
wr.close();
// Representing the input stream
InputStream in = httpURLConnection.getInputStream();
// Preparing input stream bytes to be decoded to charset
InputStreamReader inputStreamReader = new InputStreamReader(in);
StringBuilder dataBuffer = new StringBuilder();
// Translates input stream bytes to charset
int inputStreamData = inputStreamReader.read();
while (inputStreamData != -1) {
char current = (char) inputStreamData;
inputStreamData = inputStreamReader.read();
// concatenates data characters from input stream
dataBuffer.append(current);
}
data = dataBuffer.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
// Disconnects socket after using
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
Log.e("TAG", data);
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// expecting a response code fro my server upon receiving the POST data
Log.e("TAG", result);
Posts.PostsDetails postsHelper = new Posts().new PostsDetails();
// For posts
try {
if (postsHelper.getIsPDCalled()){
JSONObject pJObj = new JSONObject(result);
JSONArray pJObjArray = pJObj.getJSONArray("posts");
for (int i = 0; i < pJObjArray.length(); i++) {
JSONObject pJObj_data = pJObjArray.getJSONObject(i);
postsHelper.setPost(pJObj_data.getInt("id"), "post_title", "post_content");
}
}
} catch (JSONException e) {
//Toast.makeText(JSonActivity.this, e.toString(), Toast.LENGTH_LONG).show();
Log.d("Json","Exception = "+e.toString());
}
}
}
}
Login.java
public class Login extends AppCompatActivity {
Button LoginButton;
EditText uUserName, uPassWord;
WSAdapter.SendAPIRequests AuthHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//SetupHomeBtn = (ImageButton) findViewById(R.id.SetupHomeBtn);
LoginButton = (Button) findViewById(R.id.LoginButton);
uUserName = (EditText) findViewById(R.id.LoginUserBox);
uPassWord = (EditText) findViewById(R.id.LoginPassBox);
//AuthHelper = new WSAdapter().new SendDeviceDetails();
// Moves user to the main page after validation
LoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// gets the username and password from the EditText
String strUserName = uUserName.getText().toString();
String strPassWord = uPassWord.getText().toString();
// API url duh
String APIUrl = "http://192.168.0.18:8000/token-auth/";
// If the user is authenticated, then transfer to the MainActivity page
if (APIAuthentication(strUserName, strPassWord, APIUrl)){
startActivity(new Intent(Login.this, Posts.class));
}
}
});
}
private boolean APIAuthentication(String un, String pw, String url){
// when it wasn't static -> AuthHelper = new WSAdapter().new SendAPIRequests();
AuthHelper = new WSAdapter.SendAPIRequests();
JSONObject postData = new JSONObject();
try {
// Attempt to input info to the Django API
postData.put("username", un);
postData.put("password", pw);
// Putting the data to be posted in the Django API
AuthHelper.execute(url, postData.toString());
return true;
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
}
I was expecting my onPostExecute to be called and store data for my posts arrays.

Okay this is a nice example of async tasks. The problem here is when you call an async task then the code below will continue to execute even when the async task hasn't finished. So what happens in your case:
You fetch the posts and then ask to display them on the exact moment that the async function is still getting the posts. So of course the List is empty.
You can fix this by using the await keyword. This keyword stops the rest of your code from executing until that line has been executed. So change:
postDetailsHelper.callPostDetails("192.168.0.18:8000/api");
to:
await postDetailsHelper.callPostDetails("192.168.0.18:8000/api");
Now the reason that the login does work is because you call that function within the if statement. If you would store the return value of that function in a boolean first then it wouldn't work either.

Related

Results from AsyncTask not getting posted to a TextView of Activity

So I was trying to retrieve all the posts from the REST API I made to be outputted to a textview in my Posts activity. I can successfully retrieve the JSON Objects and store them in their corresponding ArrayLists. However, whenever I call my ListPosts function from my Posts activity within the AsyncTask's onPostExecute, its saying that my postsSect textview is null.
I am thinking that for some reason the R.id is not getting contacted, even though I declared it in onCreate of my Posts. Because of this I'm getting this error message in my logcat:
01-14 21:43:57.022 16588-16588/com.example.android.androidcraftsappprototype E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.androidcraftsappprototype, PID: 16588
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
at android.support.v7.app.AppCompatDelegateImpl.<init>(AppCompatDelegateImpl.java:249)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:182)
at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:520)
at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:191)
at com.example.android.androidcraftsappprototype.WSAdapter$SendPostsRequest.onPostExecute(WSAdapter.java:186)
at com.example.android.androidcraftsappprototype.WSAdapter$SendPostsRequest.onPostExecute(WSAdapter.java:104)
at android.os.AsyncTask.finish(AsyncTask.java:695)
at android.os.AsyncTask.-wrap1(Unknown Source:0)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:712)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Posts.java
public class Posts extends AppCompatActivity {
TextView postsSect;
Button postsDoneBtn;
WSAdapter.SendPostsRequest PostsHelper;
StringBuilder postsBuffer = new StringBuilder();
#Override
protected void onResume(){
super.onResume();
PostsDetails postDetailsHelper = new PostsDetails();
//postDetailsHelper.ListPosts();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_posts);
postsDoneBtn = (Button) findViewById(R.id.PostsDoneButton);
postsSect = (TextView) findViewById(R.id.PostsSection);
PostsDetails postDetailsHelper = new PostsDetails();
postDetailsHelper.callPostDetails("http://192.168.0.18:8000/api/");
//postDetailsHelper.ListPosts();
postsDoneBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Posts.this, MainActivity.class));
}
});
}
public class PostsDetails {
//String post_title, post_content;
ArrayList<Integer> post_id = new ArrayList<Integer>();
ArrayList<String> post_title = new ArrayList<String>();
ArrayList<String> post_content = new ArrayList<String>();
boolean isPDCalled;
// sets if Post details are called
// checks if postsDetails functions are called for AsyncTask
boolean getIsPDCalled(){
return isPDCalled;
}
// calls the execute for AsyncTask
private void callPostDetails(String theurl){
PostsHelper = new WSAdapter().new SendPostsRequest();
// executes AsyncTask
PostsHelper.execute(theurl);
}
// sets values for the posts arrays
public void setPost(int p_id, String p_title, String p_content) {
this.post_id.add(p_id);
this.post_title.add(p_title);
this.post_content.add(p_content);
}
public ArrayList<Integer> getPostID() {
return this.post_id;
}
public ArrayList<String> getPostTitle() {
return this.post_title;
}
public ArrayList<String> getPostContent() {
return this.post_content;
}
// Lists the posts from the database
public void ListPosts() {
/////////// add functionality if a post was deleted and was clicked
int lastFrJSONArray = getPostID().size() - 1;
postsSect = (TextView) findViewById(R.id.PostsSection);
// outputs the id of the very first post, something to put to the textview
postsSect.setText("id: " + getPostID().get(0) + "\n");
for (int i = lastFrJSONArray; i >= 0; i--)
{
// appending the titles and contents of the current post
postsSect.append("title: " + getPostTitle().get(i) + "\n");
postsSect.append("content: " + getPostContent().get(i) + "\n");
// if this is the last post, then don't need to append id for the next post.
if (i != 0) {
postsSect.append("id: " + getPostID().get(i) + "\n");
}
}
}
}
}
WSAdapter.java
public class WSAdapter {
/*#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}*/
public class SendPostsRequest extends AsyncTask<String, String, String> {
TextView postsSect;
// Add a pre-execute thing
HttpURLConnection urlConnection;
private WeakReference<Activity> mPostReference;
/*public SendPostsRequest(Activity activity){
mPostReference = new WeakReference<Activity>(activity);
}*/
#Override
protected String doInBackground(String... params) {
StringBuilder result = new StringBuilder();
try {
urlConnection = (HttpURLConnection) new URL(params[0]).openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
}catch( Exception e) {
e.printStackTrace();
}
/*finally {
urlConnection.disconnect();
}*/
return result.toString();
}
#Override
protected void onPostExecute(String result) {
// expecting a response code fro my server upon receiving the POST data
Log.e("TAG", result);
Posts.PostsDetails postsHelper = new Posts().new PostsDetails();
// For posts
try {
JSONArray pJObjArray = new JSONArray(result);
// algorithm for parsing the JSONArray from the Django REST API
for (int i = 0; i < pJObjArray.length(); i++) {
// puts the current iterated JSON object from the array to another temporary object
JSONObject pJObj_data = pJObjArray.getJSONObject(i);
// inputs necesarry elements to the ListPosts function
postsHelper.setPost(pJObj_data.getInt("id"), pJObj_data.getString("post_title"), pJObj_data.getString("post_content"));
}
} catch (JSONException e) {
//Toast.makeText(JSonActivity.this, e.toString(), Toast.LENGTH_LONG).show();
Log.d("Json","Exception = "+e.toString());
}
postsHelper.ListPosts();
}
}
}
First of all restructure your code. And for setting text make those fields static which you want to use and then set their values in the onPostExecute of AsyncTask or else you can return the jsonstring as it is to your activity and then parse it there and set values for better readability.

server connection thread too late than onCreate

I'm making app which get server data from mvc spring server.
If client login success in main Activity, app try to get data from server, and use list view show data in next activity.
It works clear in first login, but when I turn back on main Activity, and try login again, next activity doesn't show anything.
I used logs to find problem and I found that when client login again, next activity's onCreate() and onResume() works too fast. My app uses thread and get data from server, logs says after onCreate and onResume works and my thread get data from server.
So this is my problem
1 App uses thread to get data from server
2 First try works but after thread is too late than onResume and onCreate in activity
3 should I have to make thread more fast? or use flags or something make onCreate and onResume works after thread works end? or does my code have problems?
This is my activity which show data from server
public class ServerListActivity extends AppCompatActivity {
public static ArrayList<ServerListItem> serverListItemArrayList;
public static ArrayList<ServerListItem> scrollEventServerListItemList;
public TextView serverListInfoTextView;
private ProgressBar progressBar;
private boolean lockListView;
private boolean isThisLastItemVisibleFlag;
private ServerListViewAdapter serverListViewAdapter;
private int currentPageNum;
public Handler msgHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
lockListView = false; // scroll event
currentPageNum = 0; // scroll event
isThisLastItemVisibleFlag = false; // scroll event
scrollEventServerListItemList = new ArrayList<>();
serverListItemArrayList = new ArrayList<>();
msgHandler = new Handler();
super.onCreate(savedInstanceState);
ServerListManager serverListManager = new ServerListManager(msgHandler);
serverListManager.getServerList();
setContentView(R.layout.activity_server_list);
ImageButton turnBackBtn = findViewById(R.id.turn_back_btn);
serverListInfoTextView = findViewById(R.id.server_list_Info);
ListView serverListView = findViewById(R.id.server_list_view);
progressBar = findViewById(R.id.progressBar);
serverListViewAdapter = new ServerListViewAdapter(scrollEventServerListItemList, R.layout.server_list_item, getApplicationContext());
serverListView.setAdapter(serverListViewAdapter);
progressBar.setVisibility(View.GONE);
serverListView.setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);
System.out.println(serverListItemArrayList.size());
setServerListInfo(serverListItemArrayList);
and this is my thread
public class ServerListManager {
private final static int SERVER_PROBLEM = 666;
private Handler handler;
public ServerListManager(Handler handler) {
this.handler = handler;
}
public void getServerList() {
new Thread(new Runnable() {
#Override
public void run() {
HttpURLConnection connection = null;
StringBuilder stringBuffer = new StringBuilder();
try {
URL url = new URL("my ip and blah balh");
connection = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
if (connection != null) {
connection.setConnectTimeout(5000);
connection.setUseCaches(false);
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
String line = bufferedReader.readLine();
if (!"".equals(line)) {
stringBuffer.append(line);
Log.i("ServerListManager", stringBuffer.toString());
}
setServerListItem(stringBuffer.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
}
private void setServerListItem(String dataFromServer) {
Log.i("ServerListManager", "setServerListItem() works ");
ArrayList<ServerListItem> serverListItems = new ArrayList<>();
JsonParser jsonParser = new JsonParser();
JsonObject jsonObjectFirst = (JsonObject) jsonParser.parse(dataFromServer);
if (!String.valueOf(jsonObjectFirst.get("status")).equals("\"200\"")) {
Message message = new Message();
message.what = SERVER_PROBLEM;
handler.sendMessage(message);
} else {
String serverListJsonVersion = String.valueOf(jsonObjectFirst.get("serverModelList"));
JsonArray jsonArray = (JsonArray) jsonParser.parse(serverListJsonVersion);
Gson gson = new Gson();
for (JsonElement jsonElement : jsonArray) {
ServerListItem serverListItem = gson.fromJson(jsonElement, ServerListItem.class);
serverListItems.add(serverListItem);
}
ServerListActivity.serverListItemArrayList = serverListItems;
}
}
You can try using AsyncTask
private class AsyncCaller extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
//can call progress bar here to show loading process
}
#Override
protected Void doInBackground(Void... params) {
//this method will be running on background thread
//so don't update UI from here
//do your long running http tasks here,
//you don't want to pass argument and you
//can access the parent class' variable url over here
// call your server data here
serverListManager.getServerList();
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//this method will be running on UI thread
//Show the result obtained from doInBackground
//this executed after doInBackground so after you get data from doInBackground
//you can set your adapter here
}
}
Then you can execute AsyncTask like this
new AsyncCaller().execute();

Android Translation application using yandex api showing result in emulator text view but not in real device

I am trying to make a translation application from English to Bangla using Yandex API.
It works fine in the emulator but in the real device it shows result for only one word in the text view but when writing a sentence it shows null / nothing.
I think the problem is buffer overflow but don't know how to fix it for the real device. Here are some reference pictures. In the emulator the result works fine:
In the real device it shows empty in text view:
But it works fine when a single word is used in real device.
Here is the code for my Asynctask:
public class
TranslatorBackgroundTask extends AsyncTask<String, Void, String> {
//Declare Context
Context ctx;
//Set Context
TranslatorBackgroundTask(Context ctx){
this.ctx = ctx;
}
String resultString;
#Override
protected String doInBackground(String... params) {
//String variables
String textToBeTranslated = params[0];
String languagePair = params[1];
String jsonString;
try {
//Set up the translation call URL
String yandexKey = "trnsl.1.1.20170823T130435Z.79a583874abfc8ff.61e23593359fdc92452e69a3d5ec05347fc4180b";
String yandexUrl = "https://translate.yandex.net/api/v1.5/tr.json/translate?key=" + yandexKey
+ "&text=" + textToBeTranslated + "&lang=" + languagePair;
URL yandexTranslateURL = new URL(yandexUrl);
//Set Http Conncection, Input Stream, and Buffered Reader
HttpURLConnection httpJsonConnection = (HttpURLConnection) yandexTranslateURL.openConnection();
InputStream inputStream = httpJsonConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
//Set string builder and insert retrieved JSON result into it
StringBuilder jsonStringBuilder = new StringBuilder();
while ((jsonString = bufferedReader.readLine()) != null) {
jsonStringBuilder.append(jsonString + "\n");
}
//Close and disconnect
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
inputStream.close();
httpJsonConnection.disconnect();
//Making result human readable
resultString = jsonStringBuilder.toString().trim();
//Getting the characters between [ and ]
resultString = resultString.substring(resultString.indexOf('[')+1);
resultString = resultString.substring(0,resultString.indexOf("]"));
//Getting the characters between " and "
resultString = resultString.substring(resultString.indexOf("\"")+1);
resultString = resultString.substring(0,resultString.indexOf("\""));
Log.d("Translation Result:", resultString);
return jsonStringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//String text = String.valueOf(resultString);
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
MainActivity.tvTranslatedText.setText(resultString);
Toast.makeText(ctx, resultString, Toast.LENGTH_LONG).show();
super.onPostExecute(result);
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
And the code for the main activity:
public class MainActivity extends AppCompatActivity{
Context context=this;
private static final int REQUEST_CODE = 1234;
static TextView tvTranslatedText;
EditText etUserText;
Button buTranslate;
Button buSpeak;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_activity_main);
tvTranslatedText = (TextView)findViewById(R.id.tvTranslatedText);
etUserText = (EditText)findViewById(R.id.etUserText);
buTranslate = (Button)findViewById(R.id.buTranslate);
buSpeak = (Button)findViewById(R.id.buSpeak);
}
public void buTranslate(View view) {
//Default variables for translation
String textToBeTranslated = "";
textToBeTranslated= etUserText.getText().toString();
String languagePair = "en-bn"; //English to bengali ("<source_language>-<target_language>")
//Executing the translation function
Translate(textToBeTranslated,languagePair);
}
//Function for calling executing the Translator Background Task
void Translate(String textToBeTranslated, String languagePair){
TranslatorBackgroundTask translatorBackgroundTask= new TranslatorBackgroundTask(context);
String translationResult = "";
translationResult = String.valueOf(translatorBackgroundTask.execute(textToBeTranslated,languagePair)); // Returns the translated text as a String
Log.d("Translation Result",translationResult); // Logs the result in Android Monitor
}
//Speak button activities
public void buSpeak(View view) {
startVoiceRecognitionActivity();
}
private void startVoiceRecognitionActivity()
{
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak to translate");
startActivityForResult(intent, REQUEST_CODE);
}
/**
* Handle the results from the voice recognition activity.
*/
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
if (data != null) {
//pull all of the matches
ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
String topResult = matches.get(0);
EditText AutoText = (EditText) findViewById(R.id.etUserText);
AutoText.setText(topResult);
}
}
}
}
The error message:
Caused by: com.google.android.apps.gsa.shared.exception.GsaIOException: Error code: 393238 | Buffer overflow, no available space.
Why didn't you add a listener to your sample code?
Try adding these on onCreate in MainActivity:
buTranslate.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
buTranslate(view);
}
}
);
Update:
There was another issue. Emulators on android sdk 16 don't show Unicode properly. Thats why you don't see your results, as those are Unicodes. Try Log to print your resultString.

Not able to send JSON response to other activity and show it in toast

I am able to register json data to my server, I am even getting response, but not able to show it in toast as well as send it to other activity (main activity).
I converted the response to string and tried to send to my mainactivity using getter but I am not able to see it in Log.i, even in toast that I mentioned. Here's my code:
class SendJsonDataToServer extends AsyncTask<String, String, String> {
String j;
#Override
protected String doInBackground(String... params) {
String JsonResponse = "";
String JsonDATA = params[0];
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
try {
URL url = new URL("http://gstedge.com/test/invoice/api.php?param=signup");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
// is output buffer writter
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
//set headers and method
Writer writer = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8"));
writer.write(JsonDATA);
// json data
writer.close();
InputStream inputStream = urlConnection.getInputStream();
//input stream
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String inputLine;
while ((inputLine = reader.readLine()) != null)
buffer.append(inputLine + "\n");
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
JsonResponse = buffer.toString();
j= JsonResponse;
//response data
Log.i("o/p:", JsonResponse);
//send to post execute
}
catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("wtf", "Error closing stream", e);
}
}
}
return JsonResponse;
}
I was not able to get response in onpostexecute as well so I removed it and thought to convert it in string and send it using getter and parse it in other activity. I am able to see response in log.i("o/p") mentioned above in the code, but I don't know why its not getting sent.
Here's my mainactivity code:
public class MainActivity extends AppCompatActivity {
EditText emailview, numberview, pwview;
Button registerview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
emailview = (EditText) findViewById(R.id.et1);
numberview = (EditText) findViewById(R.id.et2);
pwview = (EditText) findViewById(R.id.et3);
registerview = (Button) findViewById(R.id.btn1);
}
public void hit(View v) {
String email = emailview.getText().toString();
String contact = numberview.getText().toString();
String pw = pwview.getText().toString();
JSONObject a = new JSONObject();
try {
a.put("mail", email);
a.put("num", contact);
a.put("pass", pw);
} catch (JSONException e) {
e.printStackTrace();
}
if (a.length() > 0) {
new SendJsonDataToServer().execute(String.valueOf(a));
}
SendJsonDataToServer S = new SendJsonDataToServer();
String Jr = S.getJR();
Log.i("out:",Jr);
Toast.makeText(MainActivity.this, Jr, Toast.LENGTH_LONG).show();
Intent i= new Intent(MainActivity.this,UserAreaActivity.class);
startActivity(i);
}
}
The toast I see is empty.
Explanation:
Because you are creating two different objects of SendJsonDataToServer
First:
new SendJsonDataToServer().execute(String.valueOf(a));
Second:
SendJsonDataToServer S = new SendJsonDataToServer();
So these two objects will get different memory allocation. when you get response by this code
String Jr = S.getJR();
then you will get the response that was created in different object from the object you got response. So Jr will be obviously empty. That's why you cannot print the response that you expect.
Solution:
First:
You need to execute
Toast.makeText(MainActivity.this, Jr, Toast.LENGTH_LONG).show();
in
#Override
protected void onPostExecute(String result) {
Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();
}
method in your AsyncTask like this.
Second:
If you want to send this result to your second activity then you should write code like this in your onPostExecute method.
#Override
protected void onPostExecute(String result) {
Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();
Intent i = new Intent(MainActivity.this, UserAreaActivity.class);
i.putExtra("result", result);
startActivity(i);
}
and write this code in onCreate() method of UserAreaActivity
Bundle bundle = getIntent().getExtras();
String result = bundle.getString("result");
Toast.makeText(UserAreaActivity.this, result, Toast.LENGTH_LONG).show();
Now you will be able to use result in this activity.

Android listview not getting populated with data

I am new to Android Studio and have a simple android view i am working on. A button click makes a call to the foursquare API and get backresults for starbucks around my location that I parse and am trying to set to the adapter for the listbox on the same view. If i put a breakpoint in the OnPostExecute() I see the mFoursquare adapter that I set for the listview has two json string results in the mFoursquareAdapter , I even call the
mFoursquareAdapter.notifyDataSetChanged();
in it but the view does not get refreshed with the results. I have posted the code below. Can anyone please point out what I am doing wrong or need to change since I already have the results and need to get this done...Your help and feedback very much appreciated! thanks
public class FoursquareInfoFragment extends android.app.Fragment {
private ArrayAdapter<String> mFoursquareAdapter;
public FoursquareInfoFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Dummy data for the ListView. Here's the sample weekly forecast
String[] data = {
"Sample Foursquare Data",
};
List<String> foursquareList = new ArrayList<String>(Arrays.asList(data));
mFoursquareAdapter = new ArrayAdapter<String>(
getActivity(), // the current context ie the activity
R.layout.fragment_my, // the name of the layout Id
R.id.textViewFoursquare, // the Id of the TextView to populate
foursquareList);
View rootView = inflater.inflate(R.layout.fragment_my, container, false);
//View resultsView = inflater.inflate(R.layout.results, container, false);
View resultsView = inflater.inflate(R.layout.fragment_my, container, false);
ListView listView = (ListView) resultsView.findViewById(R.id.listview_FoursquareInfo);
listView.setAdapter(mFoursquareAdapter);
Button btnGetFoursquareData = (Button) rootView.findViewById(R.id.btnFoursquare);
btnGetFoursquareData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FetchFoursquareDataTask fetch = new FetchFoursquareDataTask();
fetch.execute("Starbucks");
}
});
return rootView;
}
public class FetchFoursquareDataTask extends AsyncTask<String, Void, String[]> {
private final String LOG_TAG = FetchFoursquareDataTask.class.getSimpleName();
#Override
protected void onPostExecute(String[] result) {
if (result != null) {
mFoursquareAdapter.clear();
for (String ItemStr : result) {
mFoursquareAdapter.add(ItemStr);
}
mFoursquareAdapter.notifyDataSetChanged();
}
}
#Override
protected String[] doInBackground(String... params) {
// If there's no venue category, theres nothing to look up. Verify the size of the params.
if (params.length == 0) {
return null;
}
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String foursquareJsonStr = null;
try {
// Build Foursquare URI with Parameters
final String FOURSQUARE_BASE_URL =
"https://api.foursquare.com/v2/venues/search";
final String client_id = "client_id";
final String client_secret = "client_secret";
final String v = "20130815";
final String near = "Dunwoody, Ga";
final String query = "Starbucks";
final String limit = "2";
Uri builtUri = Uri.parse(FOURSQUARE_BASE_URL).buildUpon()
.appendQueryParameter("client_id", client_id)
.appendQueryParameter("client_secret", client_secret)
.appendQueryParameter("v", v)
.appendQueryParameter("near", near)
.appendQueryParameter("query", query)
.appendQueryParameter("limit", limit)
.build();
URL url = new URL(builtUri.toString());
// Create the request to Foursquare, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
foursquareJsonStr = null;
return null;
}
foursquareJsonStr = buffer.toString();
Log.v(LOG_TAG, "Foursquare JSON String: " + foursquareJsonStr);
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
// If the code didn't successfully get the fpursquare data, there's no point in attempting
// to parse it.
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("PlaceholderFragment", "Error closing stream", e);
}
}
}
String[] list = new String[]{"", ""};
try {
JSONObject foursquareJson = new JSONObject(foursquareJsonStr);
JSONObject responseObject = (JSONObject) foursquareJson.get("response");
JSONArray foursquareArray = responseObject.getJSONArray("venues");
list = new String[foursquareArray.length()];
for (int i = 0; i < foursquareArray.length(); i++) {
list[i] = foursquareArray.get(i).toString();
}
return list;
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
} finally {
Log.e(LOG_TAG, "ba");
return list;
}
}
}
}
This
mFoursquareAdapter.add(ItemStr);
Should be
foursquareList.add(ItemStr)
And you'll need to declare foursquareList properly (as a field).
You should also declare your Adapter as a field variable as well, just in case you need to reference it later

Categories

Resources