I am getting x and y values from a JSON and creating graph using GraphView. How to implement X-axis as Dates.I am sharing my code, please see what is the mistake?
Here's my code :
import android.graphics.Color;
import android.icu.text.SimpleDateFormat;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.view.Menu;
import android.view.MenuItem;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.Viewport;
import com.jjoe64.graphview.helper.DateAsXAxisLabelFormatter;
import com.jjoe64.graphview.helper.StaticLabelsFormatter;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.DataPointInterface;
import com.jjoe64.graphview.series.LineGraphSeries;
import com.jjoe64.graphview.series.OnDataPointTapListener;
import com.jjoe64.graphview.series.Series;
import java.security.Timestamp;
import java.sql.Time;
import java.text.ParseException;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.HashMap;
import java.util.ArrayList;
import java.lang.Double;
import java.util.Map;
import java.util.Random;
import garima.asynctask.library.HttpHandler;
import static com.example.garima.bitcoingraph.sortedHashMap.sortByValues;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
//URL to get JSON Array
private static String url = "https://api.blockchain.info/charts/market-price?format=json";
HashMap<String, String> valueslist;
//JSON Node Names
private static final String TAG_STATUS = "status";
private static final String TAG_NAME = "name";
private static final String TAG_UNIT = "unit";
private static final String TAG_PERIOD = "period";
private static final String TAG_DESCRIPTION = "description";
private LineGraphSeries<DataPoint> series;
//On the click of this Get Data Button we receive information from json
Button Btngetdata;
JSONArray user = null;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GraphView graph = (GraphView) findViewById(R.id.graph);
series = new LineGraphSeries<DataPoint>();
graph.addSeries(series);
series.setThickness(8);
series.setDrawDataPoints(true);
series.setOnDataPointTapListener(new OnDataPointTapListener() {
#Override
public void onTap(Series series, DataPointInterface dataPoint) {
Toast.makeText(MainActivity.this,"On Data Point clicked:"+dataPoint, Toast.LENGTH_SHORT).show();
}
});
//StaticLabelsFormatter staticLabelsFormatter = new StaticLabelsFormatter(graph);
//staticLabelsFormatter.setHorizontalLabels(new String[] { "Feb'16", "Mar'16","April'16","May'16","June'16","July'16","Aug'16","Sep'16","Oct'16","Nov'16","Dec'16","Jan'17"});
//graph.getGridLabelRenderer().setLabelFormatter(staticLabelsFormatter);
graph.getGridLabelRenderer().setLabelFormatter(new DateAsXAxisLabelFormatter(MainActivity.this));
//graph.getGridLabelRenderer().setNumHorizontalLabels(30); // only 4 because of the space
graph.getGridLabelRenderer().setHumanRounding(false);
Viewport viewport = graph.getViewport();
viewport.setYAxisBoundsManual(true);
viewport.setMinY(0);
viewport.setMaxY(1200);
viewport.setScalable(true);
viewport.setScrollable(true);
viewport.setScalableY(true);
viewport.setScrollableY(true);
//viewport.setXAxisBoundsManual(true);
valueslist = new HashMap<>();
Btngetdata = (Button) findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
#RequiresApi(api = Build.VERSION_CODES.N)
private void addEntry(String Xax, String Yax) {
//int Xaxis_val = Integer.parseInt(Xax);
//Log.i(TAG, "addEntry: value of Xaxis val is" + Xaxis_val);
float Yaxis_val = Float.parseFloat(Yax);
Log.i(TAG, "addEntry: value of Y axis is " + Yaxis_val);
Date date= new Date();
SimpleDateFormat fmtOut = new SimpleDateFormat("dd/MM/yyyy");
try {
date=fmtOut.parse(Xax);
} catch (ParseException e) {
e.printStackTrace();
}
Log.i(TAG, "addEntry: date as x is"+date);
series.appendData(new DataPoint(date, Yaxis_val), true, 200);
}
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("Main Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
AppIndex.AppIndexApi.start(client, getIndexApiAction());
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
AppIndex.AppIndexApi.end(client, getIndexApiAction());
client.disconnect();
}
private class JSONParse extends AsyncTask<Void, Void, Void> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String Status_Value = jsonObj.getString(TAG_STATUS);
String Name_Value = jsonObj.getString(TAG_NAME);
String Unit_Value = jsonObj.getString(TAG_UNIT);
String Period_Value = jsonObj.getString(TAG_PERIOD);
String Description_Value = jsonObj.getString(TAG_DESCRIPTION);
// Getting JSON Array node
JSONArray values = jsonObj.getJSONArray("values");
// looping through All Values
for (int i = 0; i < values.length(); i++) {
JSONObject c = values.getJSONObject(i);
String x_val = c.getString("x");
String y_val = c.getString("y");
// tmp hash map for single value
HashMap<String, String> val = new HashMap<>();
// adding each child node to HashMap key => value
val.put("x", x_val);
val.put("y", y_val);
// adding values to values list
valueslist.put(x_val, y_val);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
protected void onPostExecute(Void Result) {
pDialog.dismiss();
/* ListAdapter adapter = new SimpleAdapter(
MainActivity.this, valueslist,
R.layout.list_item, new String[]{"x", "y",
}, new int[]{R.id.x_var,
R.id.y_var});
lv.setAdapter(adapter); */
Log.i(TAG, "onPostExecute: value of list is" + valueslist);
ArrayList<String> xVals = new ArrayList<>();
/*ArrayList<Entry> yVals = new ArrayList<Entry>();
/*for(Map<String,String> map:valueslist){
String tagName = map.get(TAG_VALUEx);
Log.i(TAG, "onPostExecute: value is"+ tagName);
String tagNameY=map.get(TAG_VALUEy);
Log.i(TAG, "onPostExecute: value of y is"+tagNameY);
addEntry(tagName,tagNameY);
}*/
HashMap<String,String> sortedList=sortByValues(valueslist);
Log.i(TAG,"sorted hash map is "+sortedList);
for (Map.Entry<String, String> entry : sortedList.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
String tagName = entry.getKey();
long timestampString = Long.parseLong(tagName);
String value = new java.text.SimpleDateFormat("dd/MM/yyyy").
format(new java.util.Date(timestampString * 1000));
/*// String newval=value.substring(0, value.indexOf(' '));
Date date= new Date();
SimpleDateFormat fmtOut = new SimpleDateFormat("dd/MM/yyyy");
try {
date=fmtOut.parse(value);
} catch (ParseException e) {
e.printStackTrace();
}*/
String tagNameY=entry.getValue();
//Log.i(TAG, "onPostExecute: value of date is"+date);
addEntry(value,tagNameY);
}
}
}
}
Here's the error:
I/MainActivity: addEntry: date as x isTue Jan 03 00:00:00 GMT+01:00 2017
I/System.out: 1483488000 1126.7633375
I/MainActivity: addEntry: value of Y axis is 1126.7633
I/MainActivity: addEntry: date as x isWed Jan 04 00:00:00 GMT+01:00 2017
I/System.out: 1454457600 368.38
I/MainActivity: addEntry: value of Y axis is 368.38
I/MainActivity: addEntry: date as x isWed Feb 03 00:00:00 GMT+01:00 2016
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.garima.bitcoingraph, PID: 3095
java.lang.IllegalArgumentException: new x-value must be greater then the last value. x-values has to be ordered in ASC.
at com.jjoe64.graphview.series.BaseSeries.checkValueOrder(BaseSeries.java:486)
at com.jjoe64.graphview.series.BaseSeries.appendData(BaseSeries.java:408)
at com.jjoe64.graphview.series.LineGraphSeries.appendData(LineGraphSeries.java:646)
at com.jjoe64.graphview.series.BaseSeries.appendData(BaseSeries.java:464)
at com.example.garima.bitcoingraph.MainActivity.addEntry(MainActivity.java:177)
at com.example.garima.bitcoingraph.MainActivity.-wrap0(MainActivity.java)
at com.example.garima.bitcoingraph.MainActivity$JSONParse.onPostExecute(MainActivity.java:361)
at com.example.garima.bitcoingraph.MainActivity$JSONParse.onPostExecute(MainActivity.java:312)
at android.os.AsyncTask.finish(AsyncTask.java:660)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:677)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Application terminated.
java.lang.IllegalArgumentException: new x-value must be greater then
the last value. x-values has to be ordered in ASC.
I think you must order date in ascendant mode, then add to series of DataPoint.
Sorry if my english is not good.
Related
I am finding it difficult to make this simple upload. I've used all encontrandos tutorials on the internet such as Bluelist and android-sync. I already have a database created within the service. My code is as follows:
MainActivity.java
package com.example.engenharia.replicator;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import com.cloudant.sync.datastore.BasicDocumentRevision;
import com.cloudant.sync.datastore.Datastore;
import com.cloudant.sync.datastore.DatastoreException;
import com.cloudant.sync.datastore.DatastoreManager;
import com.cloudant.sync.datastore.DocumentBodyFactory;
import com.cloudant.sync.datastore.DocumentException;
import com.cloudant.sync.datastore.DocumentRevision;
import com.cloudant.sync.datastore.MutableDocumentRevision;
import com.cloudant.sync.query.IndexManager;
import com.cloudant.sync.replication.ReplicatorBuilder;
import com.cloudant.sync.replication.Replicator;
import java.io.File;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
public class MainActivity extends AppCompatActivity {
private static final String DATASTORE_MANGER_DIR = "data";
private Datastore DataStore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
URI uri = new URI(my_uri);
File path = getApplicationContext().getDir(DATASTORE_MANGER_DIR, Context.MODE_PRIVATE);
DatastoreManager manager = new DatastoreManager(path.getAbsolutePath());
DataStore = manager.openDatastore("banco0"); //banco0 is the DB created in Cloudant NoSQL service.
// Create a replicator that replicates changes from the local
// datastore to the remote database.
Replicator replicator = ReplicatorBuilder.push().to(uri).from(DataStore).build();
// Use a CountDownLatch to provide a lightweight way to wait for completion
CountDownLatch latch = new CountDownLatch(1);
Listener listener = new Listener(latch);
replicator.getEventBus().register(listener);
replicator.start();
latch.await();
replicator.getEventBus().unregister(listener);
if(replicator.getState() != Replicator.State.COMPLETE){
System.out.println("Error replicating TO remote");
System.out.println(listener.error);
} else {
System.out.println(String.format("Replicated %d documents in %d batches",
listener.documentsReplicated, listener.batchesReplicated));
}
}catch (Exception e){
e.printStackTrace();
}
}
public DocumentRevision createDocument() {
MutableDocumentRevision rev = new MutableDocumentRevision();
rev.body = DocumentBodyFactory.create(HashMap());
try {
return DataStore.createDocumentFromRevision(rev);
} catch (DocumentException e) {
//throw new RuntimeException(e);
e.printStackTrace();
return null;
}
}
public Map<String, Object> HashMap() {
HashMap<String, Object> map = new HashMap<String, Object>();
HashMap<String, String> map1 = new HashMap<String, String>();
map1.put("Street", "121");
map1.put("Street1", "12112");
map1.put("Street123", "1211111");
String[] array1 = new String[]{"Cloudant", "NoSQL", "JSON"};
map.put("address", map1);
map.put("description", "This is sample description");
map.put("skills", array1);
return map;
}
}
listener.java
package com.example.engenharia.replicator;
import com.cloudant.sync.notifications.ReplicationCompleted;
import com.cloudant.sync.notifications.ReplicationErrored;
import com.cloudant.sync.replication.ErrorInfo;
import com.google.common.eventbus.Subscribe;
import com.cloudant.sync.replication.ReplicatorBuilder;
import com.cloudant.sync.replication.Replicator;
import java.util.concurrent.CountDownLatch;
/**
* Created by engenharia on 19/08/16.
*/
public class Listener {
private final CountDownLatch latch;
public ErrorInfo error = null;
public int documentsReplicated;
public int batchesReplicated;
Listener(CountDownLatch latch) {
this.latch = latch;
}
#Subscribe
public void complete(ReplicationCompleted event) {
this.documentsReplicated = event.documentsReplicated;
this.batchesReplicated = event.batchesReplicated;
latch.countDown();
}
#Subscribe
public void error(ReplicationErrored event) {
this.error = event.errorInfo;
latch.countDown();
}
}
Executing this code I have the follow error:
CouchException: error: forbidden, reason: server_admin access is
required for this request, statusCode: 403, msg: null, cause: null
But I am the admin!
How do I fix the problem or what is the solution?
I am using below code and my textview links are clickable but i want to make specific button of whatsapp and facebook for sharing..i referred several article in stackoverflow but i want for textview. for webview i had earlier done and it was easy .please help /suggest for textview sharing. i dont want all buttons to open. i want after each listview one facebook and whatsapp icon. on click whatsapp should open with text to be shared
in textview i am adding below for whatsapp share but nothing happens
<a rel="nofollow" href="whatsapp://send?text=एक वृद्ध दंपति को लगने लगा कि उनकी क वृद्ध दंपति को लगने लगा कि उनकी याददाश्त कमजोर हो चली है। यह सुनिश्चित करने के लिये कि उन्हें कुछ नही%0A."><span class="whatsapp"> </span></a>
my java code is
tried adding this one also in java but no benefit.
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.setPackage("com.whatsapp");
if (intent != null) {
intent.putExtra(Intent.EXTRA_TEXT, msg);
startActivity(Intent.createChooser(intent, ""));
main.java code here
package com.hindishayari.funnywall.activity;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import com.hindishayari.funnywall.R;
import com.hindishayari.funnywall.adapter.SwipeDownListAdapter;
import com.hindishayari.funnywall.analytics.AnalyticsApplication;
public class MainActivity extends Activity implements SwipeRefreshLayout.OnRefreshListener {
// URLS for Fetching and Submitting to Funny Wall.
private String FetchFunnyWallURL = "http://xxxxxxxxxxxx.com/AndroidFunnyWallApp/ppppppppp.php";
private String SubmitJokeToWallURL = "http://xxxxxxxxxxxx.com/AndroidFunnyWallApp/hhhhhhhhhh.php";
private InterstitialAd mInterstitialAd;
private SwipeRefreshLayout swipeRefreshLayout;
private ListView listView;
private SwipeDownListAdapter adapter;
private ArrayList<String> jokesList;
private ArrayList<String> timeDateList;
String JokeString = null;
String []dataValues = new String[2];
int counter = 0;
TextView titleTextView;
AlertDialog alertDw;
AlertDialog.Builder builder;
Typeface font;
LinearLayout adViewLayout;
LinearLayout listViewLayout;
private Tracker mTracker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
AnalyticsApplication application = (AnalyticsApplication) getApplication();
mTracker = application.getDefaultTracker();
font = Typeface.createFromAsset(getAssets(), "HelveticaNeue-Regular.ttf");
titleTextView = (TextView) findViewById(R.id.titleID);
adViewLayout = (LinearLayout) findViewById(R.id.adViewLayoutID);
listViewLayout = (LinearLayout) findViewById(R.id.ListViewLinearLayout);
titleTextView.setTypeface(font);
dataValues[0] = "";
dataValues[1] = "";
listView = (ListView) findViewById(R.id.listView);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
jokesList = new ArrayList<>();
timeDateList = new ArrayList<>();
adapter = new SwipeDownListAdapter(this, jokesList, timeDateList);
listView.setAdapter(adapter);
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
jokesList.clear();
timeDateList.clear();
new FetchFunnyWallFromServer().execute(FetchFunnyWallURL);
}
}
);
/*
This function is to refresh the List with Swipe-Down
*/
#Override
public void onRefresh() {
jokesList.clear();
timeDateList.clear();
new FetchFunnyWallFromServer().execute(FetchFunnyWallURL);
}
#Override
protected void onResume() {
super.onResume();
}
/*
This function is to fetch all the jokes + dates from the server and store that into the jokesList
timeDateLis respectively
*/
private class FetchFunnyWallFromServer extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
return FetchFunnyWall(urls[0]);
} catch (IOException e) {
return "Sorry, We cannot retrieve credits data form the server at this moment.";
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
listView.setEnabled(false);
dataValues[0] = "";
dataValues[1] = "";
counter = 0;
jokesList.clear();
timeDateList.clear();
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
swipeRefreshLayout.setRefreshing(false);
listView.setEnabled(true);
if (result.equals("OK")) {
listView.post(new Runnable() {
#Override
public void run() {
Collections.reverse(jokesList);
Collections.reverse(timeDateList);
adapter.notifyDataSetChanged();
listView.smoothScrollToPosition(0);
}
});
}
else
{
Toast.makeText(getApplicationContext(), "Network Connection Problem. Make sure that your internet is properly connected", Toast.LENGTH_SHORT).show();
}
}
}
private String FetchFunnyWall(String myurl) throws IOException, UnsupportedEncodingException {
InputStream is = null;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setDefaultUseCaches(false);
conn.addRequestProperty("Cache-Control", "no-cache");
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
is = conn.getInputStream();
BufferedReader textReader = new BufferedReader(new InputStreamReader(is));
String readlineText;
while ((readlineText = textReader.readLine()) != null) {
if (readlineText.length() > 0 )
{
if (readlineText.equals("****")) {
continue;
}
if (readlineText.length() < 4) {
continue;
}
for (int i = 0; i < readlineText.length(); ++i) {
if (readlineText.charAt(i) == '|') {
++counter;
continue;
}
dataValues[counter] = (dataValues[counter] + readlineText.charAt(i));
}
jokesList.add(dataValues[0]);
timeDateList.add(dataValues[1]);
counter = 0;
dataValues[0] = "";
dataValues[1] = "";
}
}
}
}
}
any help will be great
While working on a project I'm getting this error
Error : method gettext() must be call from UI thread is worker
on the following line :
String url = Util.send_chat_url+"?email_id="+editText_mail_id.getText().toString()+"&message="+editText_chat_message.getText().toString();
Please Help
This is my entire code for the class ChatActivity.java
package com.example.ankit.myapplication;
import android.app.Activity;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.example.ankit.myapplication.XmppService;
import com.squareup.okhttp.OkHttpClient;
import org.jivesoftware.smack.packet.Message;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Scanner;
//import services.XmppService;
public class ChatActivity extends Activity {
EditText editText_mail_id;
EditText editText_chat_message;
ListView listView_chat_messages;
Button button_send_chat;
List<ChatObject> chat_list;
BroadcastReceiver recieve_chat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
Scanner in = new Scanner(System.in);
XmppService xm= new XmppService();
Log.d("pavan","in chat "+getIntent().getStringExtra("user_id"));
Log.d("pavan","in chat server "+Util.SERVER);
XmppService.setupAndConnect(ChatActivity.this, Util.SERVER, "",
getIntent().getStringExtra("user_id"), Util.XMPP_PASSWORD);
editText_mail_id= (EditText) findViewById(R.id.editText_mail_id);
editText_chat_message= (EditText) findViewById(R.id.editText_chat_message);
listView_chat_messages= (ListView) findViewById(R.id.listView_chat_messages);
button_send_chat= (Button) findViewById(R.id.button_send_chat);
button_send_chat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// send chat message to server
String message=editText_chat_message.getText().toString();
showChat("sent",message);
// new SendMessage().execute();
XmppService.sendMessage(ChatActivity.this, editText_mail_id.getText().toString() + Util.SUFFIX_CHAT, Message.Type.chat, message);
editText_chat_message.setText("");
}
});
recieve_chat=new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String message=intent.getStringExtra("message");
Log.d("pavan","in local braod "+message);
showChat("recieve",message);
}
};
LocalBroadcastManager.getInstance(this).registerReceiver(recieve_chat, new IntentFilter("message_recieved"));
}
private void showChat(String type, String message){
if(chat_list==null || chat_list.size()==0){
chat_list= new ArrayList<ChatObject>();
}
chat_list.add(new ChatObject(message,type));
ChatAdabter chatAdabter=new ChatAdabter(ChatActivity.this,R.layout.chat_view,chat_list);
listView_chat_messages.setAdapter(chatAdabter);
//chatAdabter.notifyDataSetChanged();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
private class SendMessage extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String url = Util.send_chat_url+"?email_id="+editText_mail_id.getText().toString()+"&message="+editText_chat_message.getText().toString();
Log.i("pavan", "url" + url);
OkHttpClient client_for_getMyFriends = new OkHttpClient();
String response = null;
// String response=Utility.callhttpRequest(url);
try {
url = url.replace(" ", "%20");
response = callOkHttpRequest(new URL(url),
client_for_getMyFriends);
for (String subString : response.split("<script", 2)) {
response = subString;
break;
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//Toast.makeText(context,"response "+result,Toast.LENGTH_LONG).show();
}
}
// Http request using OkHttpClient
String callOkHttpRequest(URL url, OkHttpClient tempClient)
throws IOException {
HttpURLConnection connection = tempClient.open(url);
connection.setConnectTimeout(40000);
InputStream in = null;
try {
// Read the response.
in = connection.getInputStream();
byte[] response = readFully(in);
return new String(response, "UTF-8");
} finally {
if (in != null)
in.close();
}
}
byte[] readFully(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
for (int count; (count = in.read(buffer)) != -1;) {
out.write(buffer, 0, count);
}
return out.toByteArray();
}
}
Do not access the Android UI toolkit from outside the UI thread
Pass editText_mail_id.getText() and editText_chat_message.getText() as parameters to your async task or set it in onPreExecute to some variable
Like :
private class SendMessage extends AsyncTask<String, Void, String> {
private String mailId;
private String msgText;
#Override
protected void onPreExecute() {
super.onPreExecute();
mailId = editText_mail_id.getText().toString();
msgText = editText_chat_message.getText().toString();
}
Change url in doInBackground as :
String url = Util.send_chat_url+"?email_id="+mailId+"&message="+msgText;
you can create class for storing your parameter like i do,
Just create one class
example :
public class MyTaskParams
{
String mailId;
String message;
public MyTaskParams(String mailId, String message)
{
this.mailId = mailId;
this.message = message;
}
}
public class SendMessage extends AsyncTask<MyTaskParams, Void, String {
#Override
protected String doInBackground(MyTaskParams... params) {
String mailId = params[0].mailId;
String message = params[0].message;
String url = Util.send_chat_url+"?email_id="+ mailId +"&message="+ message;
}
}
so you can just call like this
MyTaskParams params = new MyTaskParams(editText_mail_id.getText().toString(),editText_chat_message.getText().toString());
SendMessage myTask = new SendMessage();
myTask.execute(params);
with this code you can call SendMessage Class from any activity, dont bind your asynctask with get text because if you do that you just can use SendMessage only in that activity
Hope this can help you.
I need to show toast message when the server is not responding
when I press the login button, some parameters are passed to AgAppMenu screen which use url connection to server and get xml response in AgAppHelperMethods screen. The
probelm is when the server is busy or the network is not avaibale, I can't show toast message on catch block although it shows the log message.
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent ;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class LoginScreen extends Activity implements OnClickListener {
EditText mobile;
EditText pin;
Button btnLogin;
Button btnClear;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.agapplogin);
TextView lblMobileNo = (TextView) findViewById(R.id.lblMobileNo);
lblMobileNo.setTextColor(getResources()
.getColor(R.color.text_color_red));
mobile = (EditText) findViewById(R.id.txtMobileNo);
TextView lblPinNo = (TextView) findViewById(R.id.lblPinNo);
lblPinNo.setTextColor(getResources().getColor(R.color.text_color_red));
pin = (EditText) findViewById(R.id.txtPinNo);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnClear = (Button) findViewById(R.id.btnClear);
btnLogin.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
postLoginData();
}
});
btnClear.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
cleartext();
}
});
/*
*
* btnClear.setOnClickListener(new OnClickListener() { public void
* onClick(View arg0) {
*
* } });
*/
}
public void postLoginData()
{
if (pin.getTextSize() == 0 || mobile.getTextSize() == 0) {
AlertDialog.Builder altDialog = new AlertDialog.Builder(this);
altDialog.setMessage("Please Enter Complete Information!");
} else {
Intent i = new Intent(this.getApplicationContext(), AgAppMenu.class);
Bundle bundle = new Bundle();
bundle.putString("mno", mobile.getText().toString());
bundle.putString("pinno", pin.getText().toString());
i.putExtras(bundle);
startActivity(i);
}
}
#Override
public void onClick(View v) {
}
public void cleartext() {
{
pin.setText("");
mobile.setText("");
}
}
}
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class AgAppMenu extends Activity {
String mno, pinno;
private String[][] xmlRespone;
Button btnMiniStatement;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.agappmenu);
mno = getIntent().getExtras().getString("mno");
pinno = getIntent().getExtras().getString("pinno");
setTitle("Welcome to the Ag App Menu");
AgAppHelperMethods agapp =new AgAppHelperMethods();
// xmlRespone = AgAppHelperMethods.AgAppXMLParser("AG_IT_App/AgMainServlet?messageType=LOG&pin=" + pinno + "&mobile=" + mno + "&source=" + mno + "&channel=INTERNET");
xmlRespone = agapp.AgAppXMLParser("AG_IT_App/AgMainServlet?messageType=LOG&pin=" + pinno + "&mobile=" + mno + "&source=" + mno + "&channel=INTERNET");
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import android.view.View;
import android.view.View.OnKeyListener;
public class AgAppHelperMethods extends Activity {
private static final String LOG_TAG = null;
private static AgAppHelperMethods instance = null;
public static String varMobileNo;
public static String varPinNo;
String[][] xmlRespone = null;
boolean flag = true;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.agapphelpermethods);
}
protected AgAppHelperMethods() {
}
public static AgAppHelperMethods getInstance() {
if (instance == null) {
instance = new AgAppHelperMethods();
}
return instance;
}
public static String getUrl() {
String url = "https://demo.accessgroup.mobi/";
return url;
}
public String[][] AgAppXMLParser(String parUrl) {
String _node, _element;
String[][] xmlRespone = null;
try {
String url = AgAppHelperMethods.getUrl() + parUrl;
URL finalUrl = new URL(url);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(finalUrl.openStream()));
doc.getDocumentElement().normalize();
NodeList list = doc.getElementsByTagName("*");
_node = new String();
_element = new String();
xmlRespone = new String[list.getLength()][2];
// this "for" loop is used to parse through the
// XML document and extract all elements and their
// value, so they can be displayed on the device
for (int i = 0; i < list.getLength(); i++) {
Node value = list.item(i).getChildNodes().item(0);
_node = list.item(i).getNodeName();
_element = value.getNodeValue();
xmlRespone[i][0] = _node;
xmlRespone[i][1] = _element;
}// end for
throw new ArrayIndexOutOfBoundsException();
}// end try
// will catch any exception thrown by the XML parser
catch (Exception e) {
Toast.makeText(AgAppHelperMethods.this,
"error server not responding " + e.getMessage(),
Toast.LENGTH_SHORT).show();
Log.e(LOG_TAG, "CONNECTION ERROR FUNDAMO SERVER NOT RESPONDING", e);
}
// Log.e(LOG_TAG, "CONNECTION ERROR FUNDAMO SERVER NOT RESPONDING", e);
return xmlRespone;
}
`
AgAppHelperMethods isn't really an Activity. You've derived this class from Activity, but then you've created Singleton management methods (getInstance()) and you are instantiating it yourself. This is bad. Don't do this.
Normally Android controls the instantiation of activities. You don't ever create one yourself (with new).
It looks to me like AgAppHelperMethods just needs to be a regular Java class. It doesn't need to inherit from anything. Remove also the lifecycle methods like onCreate().
Now you will have a problem with the toast, because you need a context for that and AgAppHelperMethods isn't a Context. To solve that you can add Context as a parameter to AgAppXMLParser() like this:
public String[][] AgAppXMLParser(Context context, String parUrl) {
...
// Now you can use "context" to create your toast.
}
When you call AgAppXMLParser() from AgAppMenu just pass "this" as the context parameter.
I want show the maps of my places, based on a selection of area like business,favorites, etc.
I am using the following intent for search and display the result in the maps in Android
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps"));
startActivity(intent);
When I click the maps place as favorites it shows that place in my places.
How can I divide the places based on category in Android?
You should use the place api for getting the selection of area.
Step by step,
How to get the list of nearest place of a location.
Step 1 : Go to API Console for obtaining the Place API
https://code.google.com/apis/console/
and select on services tab
on the place service
now select API Access tab and get the API KEY
now you have a API key for getting place
Now in programming
*Step 2 * : first create a class named Place.java. This class is used to contain the property of place which are provided by Place api.
package com.android.code.GoogleMap.NearsetLandmark;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONException;
import org.json.JSONObject;
public class Place {
private String id;
private String icon;
private String name;
private String vicinity;
private Double latitude;
private Double longitude;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public Double getLatitude() {
return latitude;
}
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
public Double getLongitude() {
return longitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVicinity() {
return vicinity;
}
public void setVicinity(String vicinity) {
this.vicinity = vicinity;
}
static Place jsonToPontoReferencia(JSONObject pontoReferencia) {
try {
Place result = new Place();
JSONObject geometry = (JSONObject) pontoReferencia.get("geometry");
JSONObject location = (JSONObject) geometry.get("location");
result.setLatitude((Double) location.get("lat"));
result.setLongitude((Double) location.get("lng"));
result.setIcon(pontoReferencia.getString("icon"));
result.setName(pontoReferencia.getString("name"));
result.setVicinity(pontoReferencia.getString("vicinity"));
result.setId(pontoReferencia.getString("id"));
return result;
} catch (JSONException ex) {
Logger.getLogger(Place.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
#Override
public String toString() {
return "Place{" + "id=" + id + ", icon=" + icon + ", name=" + name + ", latitude=" + latitude + ", longitude=" + longitude + '}';
}
}
Now create a class named PlacesService
package com.android.code.GoogleMap.NearsetLandmark;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class PlacesService {
private String API_KEY;
public PlacesService(String apikey) {
this.API_KEY = apikey;
}
public void setApiKey(String apikey) {
this.API_KEY = apikey;
}
public List<Place> findPlaces(double latitude, double longitude,String placeSpacification)
{
String urlString = makeUrl(latitude, longitude,placeSpacification);
try {
String json = getJSON(urlString);
System.out.println(json);
JSONObject object = new JSONObject(json);
JSONArray array = object.getJSONArray("results");
ArrayList<Place> arrayList = new ArrayList<Place>();
for (int i = 0; i < array.length(); i++) {
try {
Place place = Place.jsonToPontoReferencia((JSONObject) array.get(i));
Log.v("Places Services ", ""+place);
arrayList.add(place);
} catch (Exception e) {
}
}
return arrayList;
} catch (JSONException ex) {
Logger.getLogger(PlacesService.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
//https://maps.googleapis.com/maps/api/place/search/json?location=28.632808,77.218276&radius=500&types=atm&sensor=false&key=your_api_key
private String makeUrl(double latitude, double longitude,String place) {
StringBuilder urlString = new StringBuilder("https://maps.googleapis.com/maps/api/place/search/json?");
if (place.equals("")) {
urlString.append("&location=");
urlString.append(Double.toString(latitude));
urlString.append(",");
urlString.append(Double.toString(longitude));
urlString.append("&radius=1000");
// urlString.append("&types="+place);
urlString.append("&sensor=false&key=" + API_KEY);
} else {
urlString.append("&location=");
urlString.append(Double.toString(latitude));
urlString.append(",");
urlString.append(Double.toString(longitude));
urlString.append("&radius=1000");
urlString.append("&types="+place);
urlString.append("&sensor=false&key=" + API_KEY);
}
return urlString.toString();
}
protected String getJSON(String url) {
return getUrlContents(url);
}
private String getUrlContents(String theUrl)
{
StringBuilder content = new StringBuilder();
try {
URL url = new URL(theUrl);
URLConnection urlConnection = url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()), 8);
String line;
while ((line = bufferedReader.readLine()) != null)
{
content.append(line + "\n");
}
bufferedReader.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return content.toString();
}
}
Now create a new Activity where you want to get the list of nearest places.
/**
*
*/
package com.android.code.GoogleMap.NearsetLandmark;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.android.code.R;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
/**
* #author dwivedi ji *
* */
public class CheckInActivity extends ListActivity {
private String[] placeName;
private String[] imageUrl;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
new GetPlaces(this,getListView()).execute();
}
class GetPlaces extends AsyncTask<Void, Void, Void>{
Context context;
private ListView listView;
private ProgressDialog bar;
public GetPlaces(Context context, ListView listView) {
// TODO Auto-generated constructor stub
this.context = context;
this.listView = listView;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
bar.dismiss();
this.listView.setAdapter(new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, placeName));
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
bar = new ProgressDialog(context);
bar.setIndeterminate(true);
bar.setTitle("Loading");
bar.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
findNearLocation();
return null;
}
}
public void findNearLocation() {
PlacesService service = new PlacesService("past your key");
/*
Hear you should call the method find nearst place near to central park new delhi then we pass the lat and lang of central park. hear you can be pass you current location lat and lang.The third argument is used to set the specific place if you pass the atm the it will return the list of nearest atm list. if you want to get the every thing then you should be pass "" only
*/
List<Place> findPlaces = service.findPlaces(28.632808,77.218276,"atm");
// Hear third argument, we pass the atm for getting atm , if you pass the hospital then this method return list of hospital , If you pass nothing then it will return all landmark
placeName = new String[findPlaces.size()];
imageUrl = new String[findPlaces.size()];
for (int i = 0; i < findPlaces.size(); i++) {
Place placeDetail = findPlaces.get(i);
placeDetail.getIcon();
System.out.println( placeDetail.getName());
placeName[i] =placeDetail.getName();
imageUrl[i] =placeDetail.getIcon();
}
}
}