Getting Force Close while parsing JSON in async task - android

I am trying to show progress dialog while the json is being parsed in background (using Async Task),but whenever i try that,I get Force Close,the json works properly whenever i use it wihout async task.
Here is my code for it :
package com.Parsing.SOAPParsing;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import org.json.JSONArray;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final String SOAP_ACTION = "http://tempuri.org/testService";
private static final String METHOD_NAME = "testService";
private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL = "http://testService/webservice.asmx";
TextView tv, optionA, optionB, optionC, optionD, optionE;
ArrayList<HashMap<String, String>> testList = new ArrayList<HashMap<String, String>>();
private String result;
int j = 0;
int k;
String questions[] = new String[12];
String opA[] = new String[12];
String opB[] = new String[12];
String opC[] = new String[12];
String opD[] = new String[12];
String opE[] = new String[12];
ListView list;
Button next;
Button previous;
int i;
String v;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.questions);
Fetch fetch = new Fetch(); // Calling async task
fetch.execute();
}
public class Fetch extends AsyncTask<String, Void, Void> {
private ProgressDialog dialog = new ProgressDialog(MainActivity.this);
#Override
public void onPreExecute() {
this.dialog
.setMessage("Loading database. Please wait..."
+ "\n\n\n\n This will will only load for once when you install the application");
this.dialog.show();
}
#Override
public Void doInBackground(String... params) {
for (k = 1; k <= 10; k++) {
try {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("QuestionId", Long.valueOf(k));
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(
URL);
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive response = (SoapPrimitive) envelope
.getResponse();
result = response.toString();
try {
JSONObject o = new JSONObject(result);
Iterator<String> it = o.keys();
while (it.hasNext()) {
JSONArray ja = o.optJSONArray(it.next());
if (ja != null) {
for (i = 0; i <= ja.length(); i++) {
String v = ja.get(i).toString();
Log.i("value", i + " = " + v);
if (i == 0) {
opA[k - 1] = v;
}
if (i == 1) {
opB[k - 1] = v;
}
if (i == 2) {
opC[k - 1] = v;
}
if (i == 3) {
opD[k - 1] = v;
}
if (i == 4) {
opE[k - 1] = v;
}
if (i == 7) {
questions[k - 1] = v;
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
tv.setText(e.getMessage());
}
}
return null;
}
public void onPostExecute(final Void unsed) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
Toast.makeText(MainActivity.this, opB[k], Toast.LENGTH_LONG)
.show();
}
}
}
}
Am stuck at this,sorry if the error is silly as i am really new to this.
Thanks for help in advance.

because your are accessing UI elements from doInBackground
#Override
public Void doInBackground(String... params) {
//YOUR CODE....
} catch (Exception e) {
tv.setText(e.getMessage()); //HERE YOU ARE ACCESSING TEXTVIEW FROM doInBackground
}
//YOUR CODE...

what you can do is :
Change the return type of Asynctask to String
Return the necessary string from doInBackground method
Update this string to your textview in onPostExecute method
i have updated your code as below.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.qualstream.telfaz.R;
public class MainActivity extends Activity {
private static final String SOAP_ACTION = "http://tempuri.org/LoadQuestionDetail";
private static final String METHOD_NAME = "LoadQuestionDetail";
private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL = "http://www.beyyondcareers.com/webservice.asmx";
TextView tv, optionA, optionB, optionC, optionD, optionE;
ArrayList<HashMap<String, String>> testList = new ArrayList<HashMap<String, String>>();
private String result;
int j = 0;
int k;
String questions[] = new String[12];
String opA[] = new String[12];
String opB[] = new String[12];
String opC[] = new String[12];
String opD[] = new String[12];
String opE[] = new String[12];
ListView list;
Button next;
Button previous;
int i;
String v;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
tv = (TextView) findViewById(R.id.textview123);
Fetch fetch = new Fetch(); // Calling async task
fetch.execute();
}
public class Fetch extends AsyncTask<Void, Void, String> {
private ProgressDialog dialog = new ProgressDialog(MainActivity.this);
#Override
public void onPreExecute() {
this.dialog
.setMessage("Loading database. Please wait..."
+ "\n\n\n\n This will will only load for once when you install the application");
this.dialog.show();
}
#Override
public String doInBackground(Void... params) {
for (k = 1; k <= 10; k++) {
try {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("QuestionId", Long.valueOf(k));
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(
URL);
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive response = (SoapPrimitive) envelope
.getResponse();
result = response.toString();
try {
JSONObject o = new JSONObject(result);
Iterator<String> it = o.keys();
while (it.hasNext()) {
JSONArray ja = o.optJSONArray(it.next());
if (ja != null) {
for (i = 0; i <= ja.length(); i++) {
String v = ja.get(i).toString();
Log.i("value", i + " = " + v);
if (i == 0) {
opA[k - 1] = v;
}
if (i == 1) {
opB[k - 1] = v;
}
if (i == 2) {
opC[k - 1] = v;
}
if (i == 3) {
opD[k - 1] = v;
}
if (i == 4) {
opE[k - 1] = v;
}
if (i == 7) {
questions[k - 1] = v;
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
return e.getMessage();
}
}
return "";
}
#Override
public void onPostExecute(String result) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
tv.setText(result);
Toast.makeText(MainActivity.this, opB[k], Toast.LENGTH_LONG)
.show();
}
}
}
}

You can't access UI elements from the doInBackground method, and the tv variable is a UI element.
tv.setText(e.getMessage());
Instead you can use the onProgressUpdate method to access UI elements. If you make a call to publishProgress in your doInBackground the onProgressUpdate method is automatically invoked.

Related

API call with AsyncTask

I am trying to use android studio to access a streaming/internet API. My API call works in Eclipse without using AsyncTask so I'm trying to use AsyncTask in Android Studio to call the API but I'm not sure why it's not working. The way I use the buffered reader and input stream are the same as the way I used them in eclipse when the call works. I also have permission to use internet in my AndroidManifest.xml.
Note: I took out my API key for obvious reasons.
import android.content.Intent;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.os.AsyncTask;
import android.view.View;
import android.widget.EditText;
import android.view.View.OnClickListener;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
private static final String TAG_DEBUG = MainActivity.class.getName();
public static final String TAG_ID = "id";
public static final String TAG_CURRENTTEMP = "currenttemp";
public static final String TAG_MAXTEMP = "maxtemp";
public static final String TAG_MINTEMP = "mintemp";
private EditText enteredzip;
private String zip;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
enteredzip = (EditText) findViewById(R.id.editText);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
}
public void onClick(View v) {
zip = enteredzip.getText().toString();
new RetrieveFeedTask().execute();
}
class RetrieveFeedTask extends AsyncTask<Void, Void, String> {
private Exception exception;
protected void onPreExecute() {
}
protected String doInBackground(Void... urls) {
String BASE_URL = "http://api.openweathermap.org/data/2.5/weather?zip=";
String API_CALL = "&APPID=key";
// Do some validation here
HttpURLConnection con = null;
InputStream is = null;
String bufferedOutput = "";
try {
con = (HttpURLConnection) (new URL(BASE_URL + zip + API_CALL)).openConnection();
con.setRequestMethod("GET");
con.setDoInput(true);
con.setDoOutput(true);
con.connect();
StringBuffer buffer = new StringBuffer();
is = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
while((line = br.readLine()) != null)
buffer.append(line + "\r\n");
is.close();
con.disconnect();
bufferedOutput = buffer.toString();
return bufferedOutput;
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
} finally {
try{
is.close();
}catch(Throwable T){}
try{
con.disconnect();
}catch(Throwable T){}
}
}
protected void onPostExecute(String response) {
if(response == null) {
//response = "THERE WAS AN ERROR";
//Toast.makeText(MainActivity.this, getResources().getString(R.string.error_et), Toast.LENGTH_LONG).show();
return;
}
//Log.i("INFO", response);
// TODO: check this.exception
// TODO: do something with the feed
Toast.makeText(MainActivity.this, response, Toast.LENGTH_LONG).show();
String id = "";
String currenttemp = "";
String maxtemp = "";
String mintemp = "";
for (int i = 0; i < response.length(); i++) {
if (response.substring(i, i + 2).equals("id")) {
id = response.substring(i + 4, i + 7);
break;
}
}
for (int i = 0; i < response.length(); i++) {
if (response.substring(i, i + 4).equals("temp")) {
currenttemp = response.substring(i + 6, i + 9);
break;
}
}
for (int i = 0; i < response.length(); i++) {
if (response.substring(i, i + 8).equals("temp_min")) {
mintemp = response.substring(i + 10, i + 13);
break;
}
}
for (int i = 0; i < response.length(); i++) {
if (response.substring(i, i + 8).equals("temp_max")) {
maxtemp = response.substring(i + 10, i + 13);
break;
}
}
launchMain2Activity(id, currenttemp, maxtemp, mintemp);
}
}
private void launchMain2Activity(String id, String currenttemp, String maxtemp, String mintemp) {
Intent Main2Activity = new Intent(MainActivity.this, Main2Activity.class);
Main2Activity.putExtra(TAG_ID, id);
Main2Activity.putExtra(TAG_CURRENTTEMP, currenttemp);
Main2Activity.putExtra(TAG_MAXTEMP, maxtemp);
Main2Activity.putExtra(TAG_MINTEMP, mintemp);
startActivity(Main2Activity);
}
try to use this :
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")) ;
UTF-8 is a method for encoding Unicode characters using 8-bit sequences.

I can't clear the listview in my fragment before populating it again?

NOTE :
First of all before writing any thing. this is not a duplicate because if it is then why I will post this here. I didn't find any of the stackoverflow similar questions' answers helpful to me at all for 2 days straight.
THE PROBLEM :
I have an activity that takes two fields of data and then go to the next activity where it has a view pager and the activity opens 2 fragments the posts and the profile. the problem here is that when I go back to the first activity to input different data and go to the fragments the listview shows duplicate data.
I tried every possible solution but none works.
I tried to clear adapter.
I tried to pass empty adapter.
I tried more things in the life cycle of the fragment but nothing.
so please I need help. thanks in advance.
package psychrating.psychrating;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Created by Ahmeed on 8/7/2017.
*/
public class PostsFragment extends Fragment {
static ListView posts_list;
Spinner list_order;
SearchView search;
String category, date, activity;
boolean get_data;
public static ArrayList<String> data = null;
static Context c;
transient ViewHolder holder;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
data = null;
activity = getArguments().getString("activity");
category = getArguments().getString("category");
date = getArguments().getString("date");
if (activity == "main") {
// get_data = true;
}else {
// get_data = true;
}
View view = inflater.inflate(R.layout.post_tab, container, false);
init(view);
posts_list.clearChoices();
if (searchResultses != null) {
searchResultses.clear();
searchResultses = null;
}
return view;
}
private void init(View view) {
posts_list = (ListView) view.findViewById(R.id.posts_list);
list_order = (Spinner) view.findViewById(R.id.list_order);
search = (SearchView) view.findViewById(R.id.search);
posts_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
holder = (ViewHolder) view.getTag();
Temp temp = new Temp();
temp.name = holder.name.getText().toString();
temp.highest = holder.highest.getText().toString();
temp.dname = holder.dname.getText().toString();
temp.date = holder.date.getText().toString();
temp.category = holder.category;
temp.sdesc = holder.sdesc;
temp.ddesc = holder.ddesc;
Intent i = new Intent(c, ProfileActivity.class);
i.putExtra("holder", temp);
startActivity(i);
}
});
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
c = context;
}
#Override
public void onResume() {
super.onResume();
searchResultses = new ArrayList<>();
new Server(this.getActivity(), "posts").execute(category, date);
}
public static final String TAG ="ahmed";
static void removeCommas() {
StringBuilder word = new StringBuilder();
for (int i = 0; i < data.size(); i++) {
for (int j = 0; j < data.get(i).length(); j++) {
char c = data.get(i).charAt(j);
if (c != ',') {
word.append(c);
}else {
words.add(word.toString());
word.delete(0, word.length());
}
}
}
}
#Override
public void onPause() {
super.onPause();
searchResultses = null;
adapter = null;
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
static void addToClass() {
SearchResults s;
int offset = 0;
for (int j = 0; j < words.size(); j += 8) {
Log.d(TAG, String.valueOf(words.size()));
s = new SearchResults();
for (int i = 0; i < 8; i++) {
offset = 1;
s.add(words.get(i * offset));
}
offset += 1;
s.init();
searchResultses.add(s);
}
}
static ArrayList<SearchResults> searchResultses = null;
static ArrayList<String> words = new ArrayList<>();
static MyCustomBaseAdapter adapter = null;
public static void fillList() {
removeCommas();
addToClass();
ArrayList<SearchResults> empty = new ArrayList<>();
adapter = new MyCustomBaseAdapter(c, empty);
adapter = new MyCustomBaseAdapter(c, searchResultses);
posts_list.setAdapter(adapter);
}
}
NOTE:
the fillList is a func that is being called by the asynctask when it finished retrieving data . which use the data variable and remove commas from data and add words to searchResult class
package psychrating.psychrating;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.io.Serializable;
import java.util.ArrayList;
/**
* Created by Ahmeed on 8/10/2017.
*/
public class MyCustomBaseAdapter extends BaseAdapter {
private static ArrayList<SearchResults> searchArrayList = null;
private LayoutInflater mInflater;
public MyCustomBaseAdapter(Context context, ArrayList<SearchResults> results) {
super();
searchArrayList = results;
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return searchArrayList.size();
}
public Object getItem(int position) {
return searchArrayList.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.name.setText(searchArrayList.get(position).getName());
holder.highest.setText(searchArrayList.get(position).getHighest());
holder.dname.setText(searchArrayList.get(position).getDName());
holder.date.setText(searchArrayList.get(position).getDate());
holder.category = searchArrayList.get(position).getCategory();
holder.sdesc = searchArrayList.get(position).getSdesc();
holder.ddesc = searchArrayList.get(position).getDdesc();
convertView.setTag(holder);
return convertView;
}
}
Server class
package psychrating.psychrating;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
/**
* Created by Ahmeed on 8/6/2017.
*/
public class Server extends AsyncTask<String, String, String> {
private Context context;
private ProgressDialog progressDialog;
private AlertDialog.Builder builder;
private String type;
private static ArrayList<String> data = null;
Server(Context context, String type) {
this.context = context;
this.type = type;
}
private void createPreDialog(String message) {
progressDialog = new ProgressDialog(context);
progressDialog.setMessage(message);
progressDialog.setCancelable(false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
progressDialog.create();
}
progressDialog.show();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
createPreDialog("hold on");
}
#Override
protected String doInBackground(String... params) {
switch (type) {
case "login":
String personName = params[0];
String personEmail = params[1];
String id = params[2];
//
OutputStreamWriter outputStreamWriter = null;
BufferedWriter writer = null;
BufferedReader bufferedReader = null;
HttpURLConnection connection = null;
String line;
String result = null;
try {
URL url = new URL("http://192.168.1.64/blabla/sign_in.php");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setConnectTimeout(8000);
outputStreamWriter = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
writer = new BufferedWriter(outputStreamWriter);
String parameters = "name=" + personName + "&email=" + personEmail + "&id=" + id;
writer.write(parameters);
writer.flush();
if (connection.getResponseCode() == 200) {
bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = bufferedReader.readLine()) != null) {
result = line;
}
} else {
result = "Server Error";
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (outputStreamWriter != null) {
outputStreamWriter.close();
}
if (connection != null) {
connection.disconnect();
}
if (bufferedReader != null) {
bufferedReader.close();
}
if (writer != null) {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
case "posts":
String category = params[0];
String date = params[1];
//
OutputStreamWriter outputStreamWriter1 = null;
BufferedWriter writer1 = null;
BufferedReader bufferedReader1 = null;
HttpURLConnection connection1 = null;
String line1 = "";
String result1 = null;
try {
URL url1 = new URL("http://192.168.1.64/blabla/posts.php");
connection1 = (HttpURLConnection) url1.openConnection();
connection1.setRequestMethod("POST");
connection1.setDoOutput(true);
connection1.setDoInput(true);
connection1.setConnectTimeout(8000);
outputStreamWriter1 = new OutputStreamWriter(connection1.getOutputStream(), "UTF-8");
writer1 = new BufferedWriter(outputStreamWriter1);
String parameters1 = "category="+category+"&date="+date;
writer1.write(parameters1);
writer1.flush();
data = new ArrayList<>();
if (connection1.getResponseCode() == 200) {
bufferedReader1 = new BufferedReader(new InputStreamReader(connection1.getInputStream()));
while ((line1 = bufferedReader1.readLine()) != null) {
data.add(line1);
}
} else {
result1 = "Server Error";
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (outputStreamWriter1 != null) {
outputStreamWriter1.close();
}
if (connection1 != null) {
connection1.disconnect();
}
if (bufferedReader1 != null) {
bufferedReader1.close();
}
if (writer1 != null) {
writer1.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result1;
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressDialog.dismiss();
switch (type) {
case "login":
switch (s) {
case "Connect Error":
createDialog(s);
break;
case "Done":
Toast.makeText(context, s, Toast.LENGTH_LONG).show();
MainActivity.updateUI(true);
break;
case "Already Exist":
MainActivity.updateUI(true);
break;
case "Server Error":
createDialog(s);
break;
}
break;
case "posts":
if (data != null) {
PostsFragment.data = data;
PostsFragment.fillList();
data = null;
}
}
}
private void createDialog(String message) {
builder = new AlertDialog.Builder(context);
builder.setTitle("Error");
builder.setMessage(message);
builder.setCancelable(false);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create();
builder.show();
}
}
Your words in PostsFragment.java makes you element duplicate, In removeCommas() method first clears the words and then add the values to the words from data.
try this. searchResultses.clear(); at the start of addToClass()
static void addToClass() {
SearchResults s;
searchResultses.clear();
int offset = 0;
for (int j = 0; j < words.size(); j += 8) {
Log.d(TAG, String.valueOf(words.size()));
s = new SearchResults();
for (int i = 0; i < 8; i++) {
offset = 1;
s.add(words.get(i * offset));
}
offset += 1;
s.init();
searchResultses.add(s);
}
}

How to implement Endless scrolling with recycler view

I want to show list of data seperated by pages that is first i want to show 5 details and then when user scrolls down then it loads 5 more by again calling the api now i have been able to show first 5 details but when scrolling it replaces previous 5 with new 5 details it is not adding data instead replacing it.
MainFile in which i want to show the data
package com.example.vinod.lcoportal;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
/**
* A simple {#link Fragment} subclass.
*/
public class StbDetailsFragment extends Fragment {
RecyclerView recycler_view_stb_details;
ArrayList<StbDetails> listitems_stb = new ArrayList<>();
String[] name = new String[50];
String[] address = new String[100];
String[] vc_stb = new String[100];
String[] city = new String[100];
String[] current_plan = new String[200];
String[] status = new String[50];
String[] csi = new String[300];
int currentpage = 0;
int pagesize = 5;
ProgressDialog pDialog;
JSONArray ja;
JSONObject jo;
String custcsi, custcity, custname, currentplan, custstatus, vc_no;
String stb_url = "http://lco.denonline.in/wapp/Service1.svc/Dashboard";
public StbDetailsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_stb_details, container, false);
currentpage = currentpage + 1;
GetStb getStb= new GetStb(currentpage, pagesize);
getStb.execute(stb_url);
return view;
}
public class MyAdapterStb extends RecyclerView.Adapter<MyAdapterStb.MyViewHolderStb> {
private ArrayList<StbDetails> list;
public MyAdapterStb(ArrayList<StbDetails> Data) {
list = Data;
}
#Override
public MyViewHolderStb onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.stb_details_cardview, parent, false);
MyViewHolderStb holder = new MyViewHolderStb(view);
return holder;
}
#Override
public void onBindViewHolder(final MyViewHolderStb holder, int position) {
holder.cust_name.setText(list.get(position).getName());
holder.cust_address.setText(list.get(position).getAddress());
holder.cust_vc.setText(list.get(position).getVc_stb_no());
holder.cust_city.setText(list.get(position).getCity());
holder.cust_plan.setText(list.get(position).getCurrentPlan());
holder.cust_status.setText(list.get(position).getStatus());
// holder.events_imageview.setImageResource(list.get(position).getImageResourceId());
// holder.events_imageview.setTag(list.get(position).getImageResourceId());
// Glide.with(getActivity()).load(list.get(position).getImageResourceId_notices()).into(holder.notices_imageview);
}
#Override
public int getItemCount() {
return list.size();
}
public class MyViewHolderStb extends RecyclerView.ViewHolder {
TextView cust_name, cust_address, cust_vc, cust_city, cust_plan, cust_status ;
public MyViewHolderStb(View v) {
super(v);
cust_name = (TextView) v.findViewById(R.id.name_stb_details);
cust_address = (TextView) v.findViewById(R.id.address_stb_details);
cust_vc = (TextView) v.findViewById(R.id.vc_stb_no_stb_details);
cust_city = (TextView) v.findViewById(R.id.city_stb_details);
cust_plan = (TextView) v.findViewById(R.id.current_plan_stb_details);
cust_status = (TextView) v.findViewById(R.id.status_stb_details);
// v.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// Intent i = new Intent(getActivity(),NoticesViewActivity.class);
// i.putExtra("notice_url",pdf[getAdapterPosition()]);
// i.putExtra("notice_title",title_notices[getAdapterPosition()]);
// startActivity(i);
// }
// });
}
}
}
public void initializeList() {
listitems_stb.clear();
for (int i = 0; i < ja.length(); i++) {
StbDetails item = new StbDetails();
item.setName(name[i]);
item.setAddress(address[i]);
item.setVc_stb_no(vc_stb[i]);
item.setCity(city[i]);
item.setCurrentPlan(current_plan[i]);
item.setStatus(status[i]);
listitems_stb.add(item);
}
}
public class GetStb extends AsyncTask<String,String,String> {
HttpURLConnection httpURLConnection;
int CurrentPage, PageSize;
public GetStb(int currentpage, int pagesize) {
CurrentPage = currentpage;
PageSize = pagesize;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Fetching Data...Please Wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
//pDialog.show();
// progress_dialog.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(String... params) {
try {
URL url = new URL(params[0]);
Log.d("DoInBackground:URL", url.toString());
//Send Post Data request
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.addRequestProperty("api_key", "XBoGycClZkJrXDVphgpN5c9Bb82fcKQ4");
httpURLConnection.addRequestProperty("gulco", "fe96632f-5173-e611-942d-005056bb1e58");
httpURLConnection.addRequestProperty("currentpage", String.valueOf(CurrentPage));
httpURLConnection.addRequestProperty("pagesize", String.valueOf(PageSize));
//)httpURLConnection.setDoOutput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setDoInput(true);
httpURLConnection.connect();
//Get the Server Response
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String response = "";
String line = "";
while ((line = bufferedReader.readLine()) != null) {
response += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
Log.d("DoInBackground", "Response:" + response);
return response;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String response) {
GridLayoutManager MyLayoutManager = new GridLayoutManager(getActivity(),1);
MyLayoutManager.setOrientation(GridLayoutManager.VERTICAL);
recycler_view_stb_details = (RecyclerView) getActivity().findViewById(R.id.recycler_view_stb_details);
recycler_view_stb_details.setHasFixedSize(true);
try {
ja = new JSONArray(response);
//ja = jo.getJSONArray("notices");
//images = new String[ja.length()];
//title = new String[ja.length()];
for (int i=0;i<ja.length();i++) {
JSONObject json = ja.getJSONObject(i);
custcsi = json.getString("CSI");
custcity = json.getString("City");
custname = json.getString("CustName");
currentplan = json.getString("Plan");
custstatus = json.getString("Status");
vc_no = json.getString("VCNO");
name[i] = custname;
csi[i] = custcsi;
city[i] = custcity;
current_plan[i] = currentplan;
vc_stb[i] = vc_no;
status[i] = custstatus;
initializeList();
}
} catch (Exception e) {
e.printStackTrace();
}
//progress_dialog.setVisibility(View.GONE);
//pDialog.dismiss();
if (listitems_stb.size() > 0 & recycler_view_stb_details != null) {
recycler_view_stb_details.setAdapter(new MyAdapterStb(listitems_stb));
}
recycler_view_stb_details.setLayoutManager(MyLayoutManager);
//pDialog.dismiss();
}
}
}
I think your problem is that every time in the public void initializeList() you call first of all listitems_stb.clear(); so your list will be cleared every time and you will lose all the previous data.
So if you wanna add other elements to the list you shouldn't clear it. Just try to delete listitems_stb.clear();.
Then for pagination see this answer here.
Hope this helps

my app doesn't add weather info to TextView (JSON)

I recently started learning JSON to use in my apps. I found a weather API (openweathermap.org) and used it on my app. the app runs fine but when I press Button, nothing happens. my source code:
import android.content.Context;
import android.hardware.input.InputManager;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.*;
import java.net.*;
import java.util.*;
import android.util.*;
import android.view.*;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import org.json.*;
public class MainActivity extends AppCompatActivity {
EditText city;
TextView weather, description;
DownloadTask DownloadTask;
public void showWeather (View view)
{
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(city.getWindowToken(), 0);
try
{
String encodedCityName = URLEncoder.encode(city.getText().toString(), "UTF-8");
DownloadTask = new DownloadTask();
DownloadTask.execute("http://api.openweathermap.org/data/2.5/weather?q=" + encodedCityName + "&appid=812f300ec742971975bbde9a2e0ac0c1");
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Error!", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
city = (EditText) findViewById(R.id.city);
weather = (TextView) findViewById(R.id.weather);
description = (TextView) findViewById(R.id.description);
}
public class DownloadTask extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection connection = null;
try
{
url = new URL(urls[0]);
connection = (HttpURLConnection) url.openConnection();
InputStream in = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != 1)
{
char current = (char) data;
result += current;
data = reader.read();
}
return result;
}
catch (Exception e)
{
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Error!", Toast.LENGTH_LONG);
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.i("Weather content", result);
try
{
JSONObject jsonObject = new JSONObject(result);
String weatherInfo = jsonObject.getString("weather");
Log.i("Weather Content", weatherInfo);
JSONArray jsonArray = new JSONArray(weatherInfo);
String getMain = "";
String getDescription = "";
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject jsonPart = jsonArray.getJSONObject(i);
getMain = jsonPart.getString("main");
getDescription = jsonPart.getString("description");
Log.i("Main", getMain);
}
if (getMain != "" && getDescription != "")
{
weather.setText(getMain);
description.setText(getDescription);
}
}
catch (JSONException e)
{
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Error!", Toast.LENGTH_LONG);
}
}
}
}
none of Toasts and Logs work.
You have an error in reading the data. You should stop reading when getting -1 not 1.
while (data != -1)
{
char current = (char) data;
result += current;
data = reader.read();
}

How to make the TTS to read all the Listview items by clicking it only once?

I have a Listview in android that can be read by TTS when you click the items it reads it, but my problem is how to make the TTS to read all the items by clicking any of the items in the listview only once?
here's the codes
package learn2crack.listview;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import learn2crack.listview.library.JSONParser;
public class MainActivity extends Activity implements TextToSpeech.OnInitListener {
ListView list;
TextView html;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "http://maps.googleapis.com/maps/api/directions/json?origin=Chicago,IL&destination=New%20York,NY&sensor=false"; //url is just a sample
//JSON Node Names
private static final String TAG_OS = "routes";
private static final String TAG_HTM = "html_instructions";
private TextToSpeech myTTS;
private int MY_DATA_CHECK_CODE = 0;
JSONArray android = null;
public void onInit(int initStatus) {
// check for successful instantiation
if (initStatus == TextToSpeech.SUCCESS) {
if (myTTS.isLanguageAvailable(Locale.US) == TextToSpeech.LANG_AVAILABLE)
myTTS.setLanguage(Locale.US);
} else if (initStatus == TextToSpeech.ERROR) {
Toast.makeText(this, "Sorry! Text To Speech failed...",
Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oslist = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
html = (TextView) findViewById(R.id.html_instruction);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
android = json.getJSONArray(TAG_OS);
for (int x = 0; x < android.length(); x++) {
JSONArray legs = android.getJSONObject(x).getJSONArray("legs");
JSONObject distance = legs.getJSONObject(0).getJSONObject("distance");
JSONObject duration = legs.getJSONObject(0).getJSONObject("duration");
JSONArray steps = legs.getJSONObject(0).getJSONArray("steps");
for (int j = 0; j < steps.length(); j++) {
String html_instructions = steps.getJSONObject(j).getString("html_instructions");
String s = html_instructions.replaceAll("<(\"[^\"]*\"|'[^']*'|[^'\">])*>", " ");
//for(int i = 0; i < android.length(); i++){
//JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
//String ver = c.getString(TAG_VER);
//String name = c.getString(TAG_NAME);
//String api = c.getString(TAG_API);
//String htm = c.getString("html_instructions");
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_HTM, s);
oslist.add(map);
list=(ListView)findViewById(R.id.list);
final ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_v,
new String[] {TAG_HTM}, new int [] {R.id.html_instruction});
list.setAdapter(adapter);
Intent checkTTSIntent = new Intent();
checkTTSIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//Toast.makeText(MainActivity.this, "You Clicked at "+oslist.get(+position).get("html"), Toast.LENGTH_SHORT).show();
parent.getAdapter();
//adapter.getItem(position).toString();
String words = adapter.getItem(position).toString();
// String words = html.getText().toString();
speakWords(words);
}
private void speakWords(String speech) {
//speak straight away
myTTS.speak(speech, TextToSpeech.QUEUE_FLUSH, null);
}
});
}
}} catch (JSONException e) {
e.printStackTrace();
}
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
//the user has the necessary data - create the TTS
myTTS = new TextToSpeech(this,(OnInitListener) this);
}
else {
//no data - install it now
Intent installTTSIntent = new Intent();
installTTSIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installTTSIntent);
}
}
}
}

Categories

Resources