JSON error loading - java

I am trying to save a simple name and load it – just to make everything clear to myself – there is no error, but when it loads it loads something different. It has something to do with Android itself.
Here is the class where I save and load (I don't use any libraries):
public class Serializer
{
private Context context;
private String fn;
public Serializer(Context con , String filename){
this.context = con;
this.fn = filename;
}
public void save(ArrayList<String> usernames) throws JSONException, IOException {
JSONArray JsonArray = new JSONArray();
JSONObject obj = new JSONObject();
for(String s : usernames){
obj.put("username" , s);
JsonArray.put(obj);
}
Writer writer = null;
OutputStream out = context.openFileOutput(fn , 0);
writer = new OutputStreamWriter(out);
writer.write(JsonArray.toString());
if(writer != null){
writer.close();
}
}
public ArrayList<String> load () throws IOException, JSONException {
ArrayList<String > strings = new ArrayList<>();
InputStream in = context.openFileInput(fn);
InputStreamReader reader = new InputStreamReader(in);
BufferedReader Reader = new BufferedReader(reader);
StringBuilder builder = new StringBuilder();
String Line;
while((Line = Reader.readLine() ) != null){
builder.append(Line);
}
JSONArray array = (JSONArray)new JSONTokener(builder.toString()).nextValue();
for(int i = 0 ; i < array.length() ; i++){
String jack = (String) array.getJSONObject(i).get("username");
strings.add(jack);
}
if(reader!=null){
reader.close();
}
return strings;
}
}
Here is my main activity whose layout is a simple layout with one TextEdit:
public class MainActivity extends AppCompatActivity {
Serializer serializer;
ArrayList<String> usernames;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
serializer = new Serializer(this,"Jacop");
TextView txtView = findViewById(R.id.txt);
usernames = new ArrayList<>();
usernames.add(txtView.toString());
try {
ArrayList<String> username = serializer.load();
txtView.setText(username.get(0));
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onResume(){
super.onResume();
try {
serializer.save(usernames);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The output (e.g what the text view shows after I close and reopen the app).
android.support.v7.widget.AppCompatEditText{73d0e9d VFED..CL. ......I. 0,0-0,0 #7f07007b app:id/txt}

You are adding an Object as String .
usernames.add(txtView.toString());
Change it to
usernames.add(txtView.getText().toString());
toString() is a method of Object class so each class have it . and android.support.v7.widget.AppCompatEditText{73d0e9d VFED..CL. ......I. 0,0-0,0 #7f07007b app:id/txt} is the string representation of the TextView object .

Related

Hello i am trying to display json data from url into listview. Nothing is displayed though

Url
private static String JSON_URL ="https://run.mocky.io/v3/aff3f637-d04f-45c0-b002-09be1a143784";
ArrayList<HashMap<String,String>> friendsList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
friendsList= new ArrayList<>();
lv = findViewById(R.id.listview);
GetData getData= new GetData();
getData.execute();
}
Getting the data
public class GetData extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... strings) {
String current = "";
try {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(JSON_URL);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(in);
int data = isr.read();
while (data != -1) {
current += (char) data;
data = isr.read();
}
return current;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
} catch (Exception e){
e.printStackTrace();
}
return current;
}
Displaying the data
#Override
protected void onPostExecute(String s) {
try{
JSONObject jsonObject= new JSONObject(s);
JSONArray jsonArray = jsonObject.getJSONArray("Friends"); //name of array
for(int i = 0; i <jsonArray.length();i++)
{
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
namey=jsonObject.getString("name");
age= jsonObject1.getString("age");
//Hashmap
HashMap<String, String> friends = new HashMap<>();
friends.put("name",namey);
friends.put("age", age);
friendsList.add(friends);
}
} catch (JSONException e) {
e.printStackTrace();
}
//Displaying the results
ListAdapter adapter = new SimpleAdapter(
MainActivity.this,
friendsList,
R.layout.row_layout,
new String[]{"name","age"},
new int[]{R.id.textView, R.id.textView2});
lv.setAdapter(adapter);
}
}
}
It doesnt display anything and i believe it has something to do with the url, but i am not quite sure so please help and thank you in advance
Your mocky JSON from https://run.mocky.io/v3/aff3f637-d04f-45c0-b002-09be1a143784 is wrong format, you need to remove the last character

Problem in parsing data from Json Google Places API to recyclerView

I would like to show users a list of bar near by them, without map. I have tried by PlaceLikelihoods, it works fine but I can not put any restriction on the types of place found and it shows a map.
So I searched by URL, but the Try / Catch always leads to the exception, the toast found there shows the good result but the list of recyclerview is not filled.
I found a similar problem that said to move the notifyDataSetChanged(), I have done it.
I find APIs and parsing very complicated to master so it's probably a stupid mistake but it's been 2 weeks and I have not yet succeeded.
Thanks for reading.
public class TestMap extends AppCompatActivity {
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private LocListAdapter mAdapter;
private EmptyStateRecyclerView mLocRecView;
private ArrayList<LocListUser> data;
private double longitudeUser;
private double latitudeUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loc);
data = new ArrayList<>();
mAdapter = new LocListAdapter(data, TestMap.this);
mLocRecView = findViewById(R.id.locRecView);
mLocRecView.setItemAnimator(new DefaultItemAnimator());
mLocRecView.setLayoutManager(new LinearLayoutManager(TestMap.this));
mLocRecView.setHasFixedSize(true);
//data.clear();
mLocRecView.setAdapter(mAdapter);
mLocRecView.clearStateDisplays();
longitudeUser = getIntent().getDoubleExtra("long", 151.2106085);
latitudeUser = getIntent().getDoubleExtra("lat", -33.8523341);
new AsyncFetch().execute();
}
private class AsyncFetch extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(TestMap.this);
HttpURLConnection conn;
URL url = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
StringBuilder sb;
sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location=").append(latitudeUser).append(",").append(longitudeUser);
sb.append("&radius=5000");
sb.append("&types=" + "bar");
sb.append("&key=API_KEY");
url = new URL(String.valueOf(sb));
} catch (MalformedURLException e) {
e.printStackTrace();
return e.toString();
}
try {
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
conn.setDoOutput(true);
} catch (IOException e1) {
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
if (response_code == HttpURLConnection.HTTP_OK) {
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
pdLoading.dismiss();
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
LocListUser locList = new LocListUser();
locList.setAddress(json_data.getString("vicinity"));
locList.setId(json_data.getString("reference"));
locList.setName(json_data.getString("place_name"));
locList.setLat(json_data.getJSONObject("geometry").getJSONObject("location").getString("lat"));
locList.setLon(json_data.getJSONObject("geometry").getJSONObject("location").getString("lng"));
locList.setType(json_data.getString("types"));
locList.setLatUser(latitudeUser);
locList.setLonUser(longitudeUser);
data.add(locList);
mAdapter.notifyDataSetChanged();
}
//mAdapter.notifyDataSetChanged();
mLocRecView.invokeState(EmptyStateRecyclerView.STATE_OK);
} catch (JSONException e) { //e.toString()
e.printStackTrace();
}
}
}
}
you are using hardcoded string
JSONArray jArray = new JSONArray("results");
you have to use
JSONArray jArray = new JSONArray(result);

Is it possible that the array map is too little for contain about 2000 items?

In my code i had caught data from a JSON file,
I executed the program, it stopped but didn't crash.
i've tried to change json file. I found one that is Smaller than the first one and so the program works.
this JSON file is made of data o premier legue(England) and contain 3 mainly data, the name, a key and a code of the squads.
public class MainActivity extends AppCompatActivity {
private ProgressDialog caric;
private String TAG = MainActivity.class.getSimpleName();
public ArrayMap<Integer, Valori> ArrayDati = new ArrayMap<>();
Button buttonProg;
TextView textViewProg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonProg = (Button) findViewById(R.id.button);
textViewProg = (TextView) findViewById(R.id.textView);
buttonProg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JsonCLASS().execute("https://raw.githubusercontent.com/openfootball/football.json/master/2015-16/en.1.clubs.json");
}
});
}
private class JsonCLASS extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
caric = new ProgressDialog(MainActivity.this);
caric.setMessage("Please wait");
caric.setCancelable(false);
caric.show();
}
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
Log.d("Response: ", "> " + line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray Arr = new JSONArray(jsonObject.getString("clubs"));
for (int i = 0; i < Arr.length(); i++){
JSONObject jsonPart = Arr.getJSONObject(i);
ArrayDati.put(i,new Valori( jsonPart.getString("key"), jsonPart.getString("name"), jsonPart.getString("code")));
textViewProg.setText(textViewProg.getText()+"key : "+ ArrayDati.get(i).Key
+"\n"+textViewProg.getText()+"name : "+ ArrayDati.get(i).Name
+"\n"+textViewProg.getText()+"code : "+ ArrayDati.get(i).Code );
}
} catch (Exception e ){
e.printStackTrace();
}
if (caric.isShowing()) {
caric.dismiss();
}
}
}
}
And a class to pass the data
public class Valori {
String Key;
String Name;
String Code;
public Valori(String key, String name, String code) {
this.Key = key;
this.Name = name;
this.Code = code;
}
}
With this code the application stops but it doesn't close.

Put row of data from back-end service into ListView

Before trying to get a row of data from a MySQL server, I used a column and managed to get that into a listView through tutorials. But for getting data in a row from a table, I couldn't manage to put it into a listView.
So what I'm trying to do is put "shift" from background worker into a listview.
PHP SQL query:
$sql = "SELECT id, employee, hours FROM selected_shifts WHERE day = '$day';";
Navigation drawer from Main Activity:
if (items[0].equals(mExpandableListTitle.get(groupPosition))) {
if (items[0].equals(mExpandableListTitle.get(childPosition))) {
String day = "Monday";
OnChoice(day);
} else if (items[1].equals(mExpandableListTitle.get(childPosition))) {
String day= "Tuesday";
OnChoice(day);
} else if (items[2].equals(mExpandableListTitle.get(childPosition))) {
String day = "Wednesday";
OnChoice(day);
} else if (items[3].equals(mExpandableListTitle.get(childPosition))) {
String day = "Thursday";
OnChoice(day);
} else if (items[4].equals(mExpandableListTitle.get(childPosition))) {
String day = "Friday";
OnChoice(day);
}
}
mDrawerLayout.closeDrawer(GravityCompat.START);
return false;
}
});
}
public void OnChoice(String day) {
String type = "choice";
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(type, day);
}
Background worker(getting data from MySQL server):
public class BackgroundWorker extends AsyncTask<String,Void,String> {
Context context;
AlertDialog alertDialog;
BackgroundWorker (Context ctx) {
context = ctx;
}
#Override
protected String doInBackground(String... params) {
String type = params[0];
String shifts_url = "***PHP LINK***";
if(type.equals("choice")) {
try {
String day = params[1];
URL url = new URL(shifts_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("day","UTF-8")+"="+URLEncoder.encode(day,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String shift="";
String line="";
while((line = bufferedReader.readLine())!= null) {
shift += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return shift;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Status");
}
#Override
protected void onPostExecute(String shift) {
//Toast the data as json
Toast.makeText(context, shift, Toast.LENGTH_LONG).show();
}
#Override
protected void onProgressUpdate(Void... values)
{
super.onProgressUpdate(values);
}
}
EDIT
Putting it into ListView:
public void onTaskCompleted(String shift) {
try {
loadIntoListView(shift);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void loadIntoListView(String shift) throws JSONException {
JSONArray jsonArray = new JSONArray(shift);
String[] list = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
list[i] = obj.getString(shift);
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
listView.setAdapter(arrayAdapter);
}
So what you want to do to pass the shift back is use a custom "Listener".
Create this
public interface TaskListener {
void onTaskCompleted(String shift);
}
And on your BackgroundWorker change the constructor as follow:
TaskListener taskListener;
BackgroundWorker(Context context, TaskListener taskListener){
this.context = context;
this.taskListener = taskListener;
}
Then on the onPostExecute method, do a taskListener.onTaskCompleted(shift).
When you call the BackgroundWorker constructor pass this as the second parameter:
BackgroundWorker backgroundWorker = new BackgroundWorker(this, this)
Then implement TaskListener on your Main and implement the method.
Something like this:
... MainActivity implements TaskListener
...
#override
onTaskCompleted(String shift) {
// You have your `shift` here to do with as you please
}
At your onPostExecute() you should add the "shift" to a dataSet in your adapter.

Android - put data into array in asynctask

I got a question that I don't know how to solve.
I am trying to achieve putting the 'question' and 'answer' into the 2D Array, but it cannot put the data into the 2D array in the asyncTask.
I am expecting I can put the 'question' and 'answer' that get in JSON Object into the 2D array. And then use the array in OnCreate method.
public class MainActivity extends Activity {
String[][] array = new String[10][4];
private TextView tvData;
int qnum = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
String quest;
String ans;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new JSONTask().execute("http://itdmoodle.hung0530.com/ptms/questions_ws.php");
Button btnNext = (Button) findViewById(R.id.btnNext);
tvData = (TextView) findViewById(R.id.textView);
for(int i=0;i<10;i++){
int z = i+1;
array[i][0] = String.valueOf(z);
}
quest = array[0][1];
ans = array[0][2];
tvData.setText(quest);
btnNext.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
}
});
}
public class JSONTask extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... params) {
HttpURLConnection conn = null;
BufferedReader reader = null;
try{
URL url = new URL(params[0]);
conn = (HttpURLConnection) url.openConnection();
conn.connect();
InputStream stream = conn.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line ="";
while((line = reader.readLine()) != null){
buffer.append(line);
}
String Json = buffer.toString();
JSONObject jsonObject = new JSONObject(Json);
JSONArray jsonArray = jsonObject.getJSONArray("Questions");
StringBuffer bufferQues = new StringBuffer();
StringBuffer bufferAns = new StringBuffer();
for(int i=0;i<jsonArray.length();i++) {
JSONObject otherJson = jsonArray.getJSONObject(i);
String question = otherJson.getString("question");
String answer = otherJson.getString("answer");
bufferQues.append(question);
bufferAns.append(answer);
array[i][1] = bufferQues.toString();
array[i][2] = bufferAns.toString();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally{
if(conn != null){
conn.disconnect();
}
try{
if(reader != null){
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
}
}
}
Asynctask executes asynchronously. It allows you to perform long running operations on a background thread(doInBackground is run on a seperate thread than main thread) and use the results to perform operations on main thread(onPostExecute runs on main thread).
What you want is to perform the operation on your 2D array in onPostExecute and not in onCreate.

Categories

Resources