How to get Facebook profile picture in android? - android

img_url = new URL("http://graph.facebook.com/" + user.getId() + "/picture?type=large");
InputStream is = img_url.openConnection().getInputStream();
Bitmap avatar;
avatar = BitmapFactory.decodeStream(is);
ivAvatar.setImageBitmap(avatar);
When i getting facebook profile picture, following error occured.
android.os.NetworkOnMainThreadException
How to solve it?

Your edited(removed) part of your question (for reference)
You're missing the second / in http:// http://graph.facebook.com/100001119045663/picture?type=large.
java.net.UnknownHostException: http:/graph.facebook.com/100001119045663/picture?type=large
The java.net.UnkownHostException describes that it can't access the URL, either a connectivity problem or malformed/invalid URL.
Second Part- Question Add
NetworkOnMainThread is quite descriptive. If you're calling functions from onCreate, onResume etc, you are executing the code on the UI thread. What this means is if you're crunching code, you can freeze the UI. You will need to create a seperate Task or Thread. For more information on what I am saying and how to implement a solution, please refer to http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html
TLDR Version...
package de.vogella.android.asynctask;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import de.vogella.android.asyntask.R;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class ReadWebpageAsyncTask extends Activity {
private TextView textView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
HTTPExample task = new HTTPExample ();
task.execute(new String[] { "http://pictureurl.com/image.jpg" });
}
private class HTTPExample extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
//urls is an array not a string, so iterate through urls.
//Get Picture Here - BUT DONT UPDATE UI, Return a reference of the object
return response;
}
#Override
protected void onPostExecute(String result) {
//Update UI
Log.i("Result", result);
}
}
}

Profile profile = Profile.getCurrentProfile();
Uri uri = profile.getProfilePictureUri(72, 72); //72 is the height and width of the profile pic, facebook will clip it for you.
new Thread(new Runnable() {
#Override
public void run() {
try{
URL newURL = new URL(uri.toString());
Bitmap profilePic = BitmapFactory.decodeStream(newURL.openConnection().getInputStream());}
catch (IOException e)
{e.printStackTrace();}
}
}).start();
This works for me.

Related

Upload image to server from imagepath stored in Sqlite database in Android

The app does the following initially
Get data from user including image and store in Sqlite database.
image path is stored in Sqlite db.
The aim of the app is to upload the data automatically and I am able to do that successfully using BroadcaseReciever for text using Volley but stuck as I don't know how the process to upload the image from Android.
I am able to retrieve the image path from the database but not sure what to do next.
I have done fair research but not getting solution when comes to upload image to server from imagepath stored in Sqlite.
Below is image path example stored in sqlite. ( I am a beginner in Android)
/storage/emulated/0/Pictures/1547728376728.jpg
Below code that I am working from.
PS : I believe the purpose of getimagepath method would be to 1. find the image 2. convert it into bytes 3. pass to Volley. I am stuck on 1. and the code might be wrong.
package com.example.narendra.e5.activities.Connectivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Base64;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.example.narendra.e5.activities.database.DatabaseHelper;
import com.example.narendra.e5.activities.others.AppSingleton;
import com.example.narendra.e5.activities.others.MySingleton;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
public class NetworkMonitor extends BroadcastReceiver {
Context context;
public Bitmap bitmap;
#Override
public void onReceive(final Context context, Intent intent) {
if (checkNetworkConnection(context)){
Toast.makeText(context, "Hello hello", Toast.LENGTH_LONG).show();
final DatabaseHelper db=new DatabaseHelper(context);
SQLiteDatabase database=db.getWritableDatabase();
Cursor cursor=db.getdataIncoming(database);
while (cursor.moveToNext()){
final String incoming=cursor.getString(cursor.getColumnIndex(DatabaseHelper.INCOMINGTIME));
Toast.makeText(context, incoming, Toast.LENGTH_LONG).show();
final String INVENID=cursor.getString(cursor.getColumnIndex(DatabaseHelper.INVENIDAPP));
final String imageurl=cursor.getString(cursor.getColumnIndex(DatabaseHelper.SLIP_IMAGE));
// get image path from database and convert it into bitmap
// Uri uri = Uri.parse(imageurl);
// bitmap=MediaStore.Images.Media.getBitmap();
StringRequest stringRequest=new StringRequest(Request.Method.POST, DatabaseHelper.SERVER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject=new JSONObject(response);
String getResponse=jsonObject.getString("response");
if (getResponse.equals("OK")){
Toast.makeText(context, "Response ok", Toast.LENGTH_LONG).show();
//db.deleteOfflineSaveOutgoingDetails(INVENID);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Response error", Toast.LENGTH_LONG).show();
}
}
){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params=new HashMap<>();
params.put("name",incoming);
// params.put("image",getimagepath(imageurl));
return params;
}
}
;
MySingleton.getInstance(context).addToRequestQue(stringRequest);
}
}
}
public boolean checkNetworkConnection(Context context){
ConnectivityManager connectivityManager= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo=connectivityManager.getActiveNetworkInfo();
return (networkInfo!=null && networkInfo.isConnected());
}
public String getimagepath(Intent imageurl){
// File imagepath=new File(String.valueOf(imageurl));
ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
Uri imagePath = imageurl.getData();
bitmap=BitmapFactory.decodeFile(String.valueOf(imagePath));
bitmap.compress(Bitmap.CompressFormat.JPEG,60,byteArrayOutputStream);
byte[] imgByte=byteArrayOutputStream.toByteArray();
return Base64.encodeToString(imgByte,Base64.DEFAULT);
}
}
For POST you can use JsonObjectRequest like this way. No need to override getParams method.
HashMap<String,String> maps=new HashMap<>();
maps.put("name",incoming);
maps.put("image",getimagepath(imageurl));
JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.POST, YOUR_URL, new JSONObject(maps), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
jsonObjectRequest.setTag("TAG");
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(2,0f));
VolleySingleton.getInstance(context).addToRequestQueue(jsonObjectRequest);
I resolved the issue by correcting the method public String getimagepath(Intent imageurl)
to this:
public String getimagepath(String imageurl){
// File imagepath=new File(String.valueOf(imageurl));
ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
//Uri imagePath = imageurl.getData();
if (imageurl !=null){
// Uri imagePath = Uri.fromFile(new File(imageurl));
bitmap=BitmapFactory.decodeFile(imageurl);
bitmap.compress(Bitmap.CompressFormat.JPEG,60,byteArrayOutputStream);
byte[] imgByte=byteArrayOutputStream.toByteArray();
return Base64.encodeToString(imgByte,Base64.DEFAULT);
}
else {
return null;
}
}

How to implement json to android correct?

I've been following a tutorial on how to show a Json arrays on android and I constantly get "Couldn't get json from server. Check internet connection!" and I can't figure out why. My Json is being generated from a php file and this works when I'm creating a list on my browser. So I'm sure my Json works.
EDIT: What adjustments do I have to do to be able to get a read from this url?
JSON array from "https://www.googleapis.com/books/v1/volumes?q=bond"
Android:
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class HomeScreen extends AppCompatActivity{
private ListView lv;
private ProgressDialog progress;
private String url="https://www.googleapis.com/books/v1/volumes?q=bond";
ArrayList<HashMap<String,String>> booklist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
booklist=new ArrayList<>();
lv= (ListView) findViewById(R.id.list);
new getBooks().execute();
}
public class getBooks extends AsyncTask<Void,Void,Void> {
protected void onPreExecute(){
super.onPreExecute();
progress=new ProgressDialog(HomeScreen.this);
progress.setMessage("Fetching JSON.,.");
progress.setCancelable(false);
progress.show();
}
protected Void doInBackground(Void...arg0){
HTTP_Handler hh = new HTTP_Handler();
String jString = hh.makeHTTPCall(url);
if (jString != null) {
try {
JSONObject jObj = new JSONObject(jString);
JSONArray books = jObj.getJSONArray("bookinfo");
for (int i = 0; i < books.length(); i++) {
JSONObject book = books.getJSONObject(i);
String name=book.getString("name");
String author=book.getString("author");
HashMap<String, String> bookdata = new HashMap<>();
bookdata.put("name", name);
bookdata.put("author", author);
booklist.add(bookdata);
}
} catch (final JSONException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
runOnUiThread(new Runnable() {
#Override
public void run() {Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check internet connection!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
protected void onPostExecute(Void Result){
super.onPostExecute(Result);
if(progress.isShowing()){
progress.dismiss();
}
ListAdapter adapter=new SimpleAdapter(
HomeScreen.this,
booklist,
R.layout.bucket_list,
new String[]{"name","author"},
new int[]{R.id.list_Name,R.id.list_author);
lv.setAdapter(adapter);
}
}
}
Does your browser have to authenticate against 'website/filename.php' to return JSON? I don't see any authentication steps going on in your code. If your code is freely available, this is probably not the issue. At first glance it appears that since now JSON is being returned from the server that this could be an issue.

share textview content with whatsapp and facebook

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

Android studio getSlotFromBufferLocked: unknown buffer error

I want to make a simple login and register app, so the user can create an account. (name, username, password)
I use WAMP and a MYSQL database where I store the accounts.
When I fill in the user info on the registration form and click register I get the following error:
09-14 09:30:39.864 2624-2638/com.example.appname.appname E/Surface﹕ getSlotFromBufferLocked: unknown buffer: 0xab7115e0
09-14 09:30:48.632 2624-2638/com.example.appname.appname E/Surface﹕ getSlotFromBufferLocked: unknown buffer: 0xab7125a0
09-14 09:30:51.940 2624-2638/com.example.appname.appname E/Surface﹕ getSlotFromBufferLocked: unknown buffer: 0xab7125a0
When I go check the database it didn't store the account.
MainActivity.java
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void userReg(View v)
{
startActivity(new Intent(this, Register.class));
}
public void userLogin(View view)
{
}
}
Register.java
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
public class Register extends Activity {
EditText ET_NAME,ET_USER_NAME,ET_USER_PASS;
String name,user_name,user_pass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register_layout);
ET_NAME = (EditText) findViewById(R.id.name);
ET_USER_NAME = (EditText) findViewById(R.id.new_user_name);
ET_USER_PASS = (EditText) findViewById(R.id.new_user_pass);
}
public void userReg(View view)
{
name = ET_NAME.getText().toString();
user_name = ET_USER_NAME.getText().toString();
user_pass = ET_USER_PASS.getText().toString();
String method = "register";
BackgroundTask backgroundTask = new BackgroundTask(Register.this);
backgroundTask.execute(method,name,user_name,user_pass);
finish();
}
}
Backgroundtask.java
import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
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.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
public class BackgroundTask extends AsyncTask<String, Void, String> {
AlertDialog alertDialog;
Context ctx;
BackgroundTask(Context ctx) {
this.ctx = ctx;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String reg_url = "http://10.0.2.2.2/webapp/register.php";
String login_url = "http://10.0.2.2.2/webapp/login.php";
String method = params[0];
if (method.equals("register")) {
String name = params[1];
String user_name = params[2];
String user_pass = params[3];
try {
URL url = new URL(reg_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream OS = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
String data = URLEncoder.encode("user", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8") + "&" +
URLEncoder.encode("user_name", "UTF-8") + "=" + URLEncoder.encode(user_name, "UTF-8") + "&" +
URLEncoder.encode("user_pass", "UTF-8") + "=" + URLEncoder.encode(user_pass, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
OS.close();
InputStream IS = httpURLConnection.getInputStream();
IS.close();
return "Registration Success...";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
}
}
register.php
<?php
require "init.php";
$name = $_POST["user"];
$user_name = $_POST["user_name"];
$user_pass = $_POST["user_pass"];
$sql_query = "insert into user_info values('$name','$user_name','$user_pass');";
if(mysqli_query($con,$sql_query))
{
//echo"<h3> Data insertion success...</h3>";
}
else{
//echo "Data insertion error..".mysqli_error($con);
}
?>
init.php
<?php
$db_name="myDBname";
$mysql_user = "root";
$mysql_pass = "root";
$server_name="localhost";
$con = mysqli_connect($server_name,$mysql_user,$mysql_pass,$db_name);
if(!$con)
{
//echo"Connection Error".mysqli_connect_error();
}
else
{
//echo"<h3> Database connection success.....</h3>";
}
?>
Edit:
This was a bug in Android that was fixed in later versions of Marshmallow
Original:
I believe that this is Marshmallow specific. Are you using a Marshmallow device?
I've noticed this error is printed out every time I switch between applications (doesn't matter which) or exit out of them, and when activities are destroyed.
I've tried running the same apps on two Nexus 5s - one running Lollipop and the other Marshmallow, and these log prints only appeared on the Marshmallow version - with every app, not just the one I'm building.
Not sure why this happens, but I opened a report here.
I think you are finishing the context before backgrounTask finish, and Context you pass no longer exist.
You can try:
Use appContext : new BackgroundTask(Register.this.getApplicationContext());
Or, Wait for BackgroundTask finish : remove finish() after .execute(...) and add finish() onPostExecute
I don't have specific problem's solution. But I had similar problem.
Anyone who has problem like this please make sure you have below code.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.<YOUR_XML_FILE_NAME>);
by using intelligence you might have choose below code:
#Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
setContentView(R.layout.<YOUR_XML_FILE_NAME>);
}
This worked for me
For more info on PersistentState
Happy coding :)
Update your android OS to 6.0.1.
This was an open issue found here. The issue is fixed in Android 6.0.1 which was publicly released recently.
It's quite strange but in my case i got this error when tried loading contacts without adding
<uses-permission android:name="android.permission.READ_CONTACTS" />
into manifest. And it disappeared just I've done it.
So my guess it's might be something with new permissions in Marshmallow.
Tested on my Nexus 5 with Android 6.0 and with targetSdkVersion 23 in build.gradle
Since that android changed permissions request (some permissions like android.permission.READ_PHONE_STATE or android.permission.READ_CONTACTS), when you ask for these permissions at runtime and dont add the permission tag (<uses-permission android:name="..." />) in manifest, you will get the error.
So just use tag permissions like old versions and add request permission at runtime in newer versions.

no communication between pub/sub code in android using zeromq

I tried to implement a simple publisher and subscriber in android using zeromq. When i try to debug it loops in subscriber recv. I dont know where i am going wrong. I think it is not able to get any data from the publisher.
Below is the code :subscriber
package com.example.jeromqps;
import java.util.*;
import org.jeromq.ZMQ;
import android.os.AsyncTask;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
public class client implements Runnable {
Messenger messenger;
public client()
{
System.out.println("client started");
}
#Override
public void run()
{
ZMQ.Context context=ZMQ.context(1);
System.out.println("collecting data from server");
ZMQ.Socket subscriber=context.socket(ZMQ.SUB);
subscriber.connect("tcp://localhost:4444");
String code="10001";
subscriber.subscribe(code.getBytes());
int totalvalue=0;
//store the data in a data structure
for(int i=0;i<10;i++)
{
byte[] msg = subscriber.recv(0);
String string=new String(subscriber.recv(0));
StringTokenizer sscanf=new StringTokenizer(string," ");
int value=Integer.valueOf(sscanf.nextToken());
String string= new String(msg);
System.out.println();
totalvalue+=value;
}
int avg=totalvalue;
Message msg1=Message.obtain();
msg1.obj=string;
try {
messenger.send(msg1);
System.out.println("sent to main");
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
subscriber.close();
context.term();
}
}
The publisher code is below
package com.example.jeromqps;
import java.util.*;
import org.jeromq.*;
public class server implements Runnable{
public server()
{
System.out.println("server started");
}
#Override
public void run()
{
ZMQ.Context context=ZMQ.context(1);
ZMQ.Socket publisher=context.socket(ZMQ.PUB);
publisher.bind("tcp://*:4444");
Random srandom=new Random(System.currentTimeMillis());
System.out.println("in server");
while(!Thread.currentThread().isInterrupted())
{ //System.out.println("in while")
int zipcode =1000 +srandom.nextInt(10000);
int temperature = srandom.nextInt(215) - 80 + 1;
String update = String.format("%05d %d", zipcode, temperature);
String update="publisher";
publisher.send(update.getBytes(),0);
}
publisher.close();
context.term();
}
}
Main is below:
package com.example.jeromqps;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.os.Handler;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends Activity implements Handler.Callback {
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new server()).start();
new Thread(new client()).start();
}
#Override
public boolean handleMessage(Message arg0)
{
String str = new String((byte[]) arg0.obj);
System.out.println("****");
System.out.println(str);
//new AlertDialog.Builder(this).setMessage(str).show();
System.out.println("****");
textView.append(str+ "\n");
return false;
}
}
In program loops at byte[] msg = subscriber.recv(0); in the subscribers class. Where am i going wrong?Am i missing something?
First of all, you've got some errors in the code:
In the publisher, update is defined twice
String update = String.format("%05d %d", zipcode, temperature);
String update= "publisher";
You have a similar problem in the subscriber code, string is defined twice...
String string = new String(subscriber.recv(0));
String string = new String(msg);
In the subscriber, you're receiving messages twice in the same iteration..
byte[] msg = subscriber.recv(0);
String string = new String(subscriber.recv(0));
...you only need this in the loop to receive...
String string = new String(subscriber.recv(0));
Try fixing those problems and see how far you get...
This isn't a solution to the question posted here, but reading this question I noticed that 0 was specified as the second parameter in the send(...) method, which subsequently matches the parameter set in the recv(...) method.
I have a simple pub/sub system set up and couldn't figure out why messages weren't being sent. I was using recv(0) but was specifying some random flag in the send(...) method. Changing the value to 0 fixed my issues.
Figured I'd post this here as it was from reading through the code in the question that I happened to have that thought. So maybe this will help someone else in the future.

Categories

Resources