I wish to retrieve data from the Laravel database and show it on the emulator of Android Studio. How can I access the data for the particular user like I view ipaddress/admin/users/1 ?
This is my getUser method in UserActivity.java:
private void getUser() {
String url = getString(R.string.api_server) + "/user";
new Thread(new Runnable() {
#Override
public void run() {
Http http = new Http(UserActivity.this, url);
http.setToken(true);
http.send();
runOnUiThread(new Runnable() {
#Override
public void run() {
Integer code = http.getStatusCode();
if (code == 200) {
try {
JSONObject response = new JSONObject(http.getResponse());
String name = response.getString("name");
String email = response.getString("email");
String gender = response.getString("gender");
tvName.setText(name);
tvEmail.setText(email);
tvCreated.setText(gender);
} catch (JSONException e) {
e.printStackTrace();
}
}else{
Toast.makeText(UserActivity.this, "Error"+code, Toast.LENGTH_SHORT).show();
}
}
});
}
}).start();
}
Related
import com.github.nkzawa.emitter.Emitter;
private Emitter.Listener onNewMessage = new Emitter.Listener() {
#Override
public void call(final Object... args) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject) args[0];
String username;
String message;
try {
username = data.getString("username");
message = data.getString("message");
} catch (JSONExpextion e) {
return;
}
}
});
}
};
When I put in this code in my project, it said "Cannot resolve method
get Activity "
then, how can I deal with this problem?
You are calling getActivity() from inner class Emitter. So you should replace getActivity() with the name of your activity followed by .this. For example the name of your activity is MainActivity, then replace getActivity() with MainActivity.this
And your code would be like this:
private Emitter.Listener onNewMessage = new Emitter.Listener() {
#Override
public void call(final Object... args) {
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject) args[0];
String username;
String message;
try {
username = data.getString("username");
message = data.getString("message");
} catch (JSONExpextion e) {
return;
}
}
});
}
};
java.lang.IllegalStateException: Your Realm is opened from a thread
without a Looper and you provided a callback, we need a Handler to
invoke your callback
I'm Writing a code that will do in background- read from a text file(inside assets) and then placing them into a realm database.But i seem to get this error
"java.lang.IllegalStateException: Your Realm is opened from a thread without a Looper and you provided a callback, we need a Handler to invoke your
callback"
In my onCreate i have this
Realm.init(context);
realm = Realm.getDefaultInstance();
ParseInBackground task = new ParseInBackground();
task.execute();
and in the do-in-background task of AsyncTask i got this
try {
realm = Realm.getDefaultInstance();
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm bgRealm) {
final ModelClass modelClass = bgRealm.createObject(ModelClass.class);
try {
InputStream file = getAssets().open("goodie.txt");
reader = new BufferedReader(new InputStreamReader(file));
final String[] line = {reader.readLine()};
while (line[0] != null) {
handler.post(new Runnable() {
#Override
public void run() {
try {
line[0] = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
String[] namelist = line[0].split(":");
String iWord = namelist[0];
String iDesc = namelist[1];
modelClass.setName(iWord);
modelClass.setDesc(iDesc);
count++;
}
});
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (realm != null)
realm.close();
}
}
}, new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
Toast.makeText(MainActivity.this, "Added " + count + "items", Toast.LENGTH_SHORT).show();
}
}, new Realm.Transaction.OnError() {
#Override
public void onError(Throwable error) {
}
}
);
} catch (Exception e) {
e.printStackTrace();
}
and a Model class called ModelClass has this
private String name;
private String desc;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
Desperately in need of help.Thanks in advance
Check http://developer.android.com/reference/android/os/Handler.html and http://developer.android.com/reference/android/os/Looper.html
Basically Realm need a way to communicate with your thread when doing asyc query, on Android, naturally Looper and Handler is the way to go.
Check this for more sample code.
https://github.com/realm/realm-java/tree/master/examples/threadExample
You need to remove Handler.post(...) from within the execute callback.
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm bgRealm) {
final ModelClass modelClass = bgRealm.createObject(ModelClass.class);
try {
InputStream file = getAssets().open("goodie.txt");
reader = new BufferedReader(new InputStreamReader(file));
final String[] line = {reader.readLine()};
while (line[0] != null) {
try {
line[0] = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
String[] namelist = line[0].split(":");
String iWord = namelist[0];
String iDesc = namelist[1];
modelClass.setName(iWord);
modelClass.setDesc(iDesc);
count++;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (realm != null)
realm.close();
}
}
}, new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
Toast.makeText(MainActivity.this, "Added " + count + "items", Toast.LENGTH_SHORT).show();
}
}, new Realm.Transaction.OnError() {
#Override
public void onError(Throwable error) {
}
}
);
} catch (Exception e) {
e.printStackTrace();
}
I hope this helps.
i wanna add user to signalR group but it says failed.
my android code to add user in group as below
HubConnection connection = new HubConnection("http://www.planetskool.in/");
HubProxy proxy = connection.createHubProxy("ChatHub");
try {
//Log.d(TAG, "connection.start()...");
SignalRFuture<Void> awaitConnection = connection.start();
// Log.d(TAG, "started");
awaitConnection.get();
// Log.d(TAG, "got");
} catch (InterruptedException e) {
/// Log.e(TAG,"InterruptedException");
e.printStackTrace();
} catch (ExecutionException e) {
//Log.e(TAG, "ExecutionException");
e.printStackTrace();
}
SignalRFuture<Void> isGroupCreated2 = proxy.invoke("JoinGroup", loginUserInfoId);
Log.d("isGroupCreated", "isGroupCreated2 = " + proxy.invoke("JoinGroup", loginUserInfoId).isDone());
proxy.on("broadcastMessage",
new SubscriptionHandler1<String>() {
#Override
public void run(final String status) {
//getApplicationContext().runOnUiThread(new Runnable() {
//public void run() {
Log.d("SignalRResult=", status);
if(status.toUpperCase().equals("False".toUpperCase())) {
new SyncMessageFromServer().execute();
}
else {
new SyncGroupMessageFromServer().execute();
}
// }
//});
}
}
, String.class);
and the code in ChatHub in MVC Web Application is
public Task JoinGroup(string groupName)
{
return Groups.Add(Context.ConnectionId, groupName);
}
public void SendAll(string rUId, string message)
{
Clients.Group(rUId).broadcastMessage(message);
}
How can i make it work to send notification to particular user
I have a problem and I can't find the solution on the internet. I saw a lot of examples but no one really answered to my problem.
I have a login page and then, after checked if the both fields (login/pass) are filled, try to connect by another thread.
public class LoginActivity extends AppCompatActivity {
private EditText login = null;
private EditText password = null;
private RadioButton radioButton = null;
private Button button = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
login = (EditText)findViewById(R.id.loginEditText);
password = (EditText)findViewById(R.id.passwordEditText);
radioButton = (RadioButton)findViewById(R.id.saveRadioButton);
button = (Button)findViewById(R.id.ConnectionButton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (login.getText().toString().equals("")
|| password.getText().toString().equals("")) {
alert(getString(R.string.alertDialoguErrorTitle), getString(R.string.UnfilledFieldLogin));
} else {
boolean haveToSave = radioButton.isChecked();
User user = User.getUser(login.getText().toString(), password.getText().toString());
try {
Intranet.login.start();
Intranet.login.join();
Intranet.login.interrupt();
Intranet.login.join();
} catch (InterruptedException e) {
alert(getString(R.string.alertDialoguErrorTitle), e.toString());
login.setText("");
password.setText("");
} finally {
if (!user._token.equals("")) {
if (haveToSave) {
// SAVE DATA
}
finish();
} else {
login.setText("");
password.setText("");
alert(getString(R.string.alertDialoguErrorTitle), getString(R.string.badLoginPassword));
}
}
}
}
});
}
public void alert(String title, String message) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(LoginActivity.this);
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setPositiveButton("Close",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// nothing
}
});
alertDialog.show();
}
}
// The class using on the other thread
public class Intranet {
public static int responseCode = 0;
public static String responseString = "";
public static Thread login = new Thread(new Runnable() {
private OkHttpClient client = new OkHttpClient();
private String url = "https://epitech-api.herokuapp.com/login";
private User user = User.getUser();
public void run() {
try {
// Build the request
RequestBody formBody = new FormEncodingBuilder()
.add("login", user._login)
.add("password", user._password)
.build();
Request request = new Request.Builder()
.url(url)
.post(formBody)
.build();
Response responses = null;
// Reset the response code
responseCode = 0;
// Make the request
responses = client.newCall(request).execute();
if ((responseCode = responses.code()) == 200) {
// Get response
String jsonData = responses.body().string();
// Transform reponse to JSon Object
JSONObject json = new JSONObject(jsonData);
// Use the JSon Object
user._token = json.getString("token");
}
} catch (IOException e) {
responseString = e.toString();
} catch (JSONException e) {
responseString = e.toString();
}
;
}
});
}
I tried a lot of solutions with join() which wait the end of the thread. But finally, all time at the second time, when I try to connect myself, an exception comes up (The thread is already started). So how can this thread still running if it's interrupted before continuing?
I tried this: when isSessionValid getDetails directly else facebook.authorize and then getDetails in onActivityResult
public class MainActivity extends Activity {
Facebook facebook = new Facebook("xxxxxxxxxxxxxxxx");
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
private SharedPreferences mPrefs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
facebook.setAccessToken(access_token);
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(this, new String[] {}, new DialogListener() {
#Override
public void onComplete(Bundle values) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token", facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
}
#Override
public void onFacebookError(FacebookError error) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onCancel() {
}
});
}else{
try {
JSONObject json = Util.parseJson(facebook.request("me"));
String facebookID = json.getString("id");
String firstName = json.getString("first_name");
String lastName = json.getString("last_name");
String email = json.getString("email");
String gender = json.getString("gender");
} catch (Exception e) {
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
try {
JSONObject json = Util.parseJson(facebook.request("me"));
String facebookID = json.getString("id");
String firstName = json.getString("first_name");
String lastName = json.getString("last_name");
String email = json.getString("email");
String gender = json.getString("gender");
} catch (Exception e) {
}
}
public void onResume() {
super.onResume();
facebook.extendAccessTokenIfNeeded(this, null);
}
}
This works fine when I have facebook app installed on my system. But If not installed i get a Web View to enter facebook credentials and in logcat shows login-success, but none of the getDetails block is called.
Here in initFacebook() function through you can login and perform you functionality, here i am fetching user's friends information.
private void initFacebook()
{
try
{
if (APP_ID == null)
{
Util.showAlert(this,"Warning","Facebook Applicaton ID must be "+ "specified before running this example: see Example.java");
}
mFacebook = new Facebook();
mAsyncRunner = new AsyncFacebookRunner(mFacebook);
mFacebook.authorize(FacebookList.this, APP_ID, new String[] {"email", "read_stream", "user_hometown", "user_location","friends_about_me", "friends_hometown", "friends_location","user_relationships", "friends_relationship_details","friends_birthday", "friends_education_history","friends_website" }, new DialogListener()
{
public void onComplete(Bundle values)
{
getHTTPConnection();
}
public void onFacebookError(FacebookError error)
{
Log.i("public void onFacebookError(FacebookError error)....","....");
}
public void onError(DialogError e)
{
Log.i("public void onError(DialogError e)....", "....");
CustomConfirmOkDialog dialog = new CustomConfirmOkDialog(FacebookList.this, R.style.CustomDialogTheme, Utils.FACEBOOK_CONNECTION_ERROR);
dialog.show();
}
public void onCancel()
{
Log.i("public void onCancel()....", "....");
}
});
SessionStore.restore(mFacebook, this);
SessionEvents.addAuthListener(new SampleAuthListener());
SessionEvents.addLogoutListener(new SampleLogoutListener());
}
catch (Exception e)
{
e.printStackTrace();
}
}
Here in getHTTPConnection(), proceeding for connection and sending fields, that we require about user's friends as here we can see that passing fields are fields=id,first_name,last_name,location,picture of friends. here you can change this fields according to application's requirements.
private void getHTTPConnection()
{
try
{
mAccessToken = mFacebook.getAccessToken();
HttpClient httpclient = new DefaultHttpClient();
String result = null;
HttpGet httpget = new HttpGet("https://graph.facebook.com/me/friends?access_token="+ mAccessToken + "&fields=id,first_name,last_name,location,picture");
HttpResponse response;
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null)
{
result = EntityUtils.toString(entity);
parseJSON(result);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
Now after successfully connecting with facebook , we are getting JSON data and further to parse it .
private void parseJSON(String data1) throws Exception,NullPointerException, JSONException
{
try
{
JSONObject jObj = new JSONObject(data1);
JSONArray jObjArr = jObj.optJSONArray("data");
int lon = jObjArr.length();
for (int i = 0; i < lon; i++)
{
JSONObject tmp = jObjArr.optJSONObject(i);
String temp_image = tmp.getString("picture"); String temp_fname = tmp.getString("first_name");
String temp_lname = tmp.getString("last_name");
String temp_loc = null;
JSONObject loc = tmp.getJSONObject("location");
temp_loc = loc.getString("name");
}
}
catch (Exception e)
{
Log.i("Exception1 is Here>> ", e.toString());
e.printStackTrace();
}
}
It is assumed that you have already added a facebook jar in to your application and for proceeding this code you can call initFacebook() in to onCreate() of your activity