How to get list of followers using Twitter Fabric Android? - java

I want to use Twitter Rest Api without using twitter4j. Fabric is fine but i couldn't find a method like gettingUserFollowers(). I don't know why it has. Anyway I want to call my user followers ids using this service. https://dev.twitter.com/rest/reference/get/followers/ids
I have looked a tutorial from fabric website(http://docs.fabric.io/android/twitter/access-rest-api.html#tweets). There is a class for getting a custom service. But i couldn't understan how i can call it sending parameter.I changed it as following
import com.twitter.sdk.android.core.TwitterApiClient;
import com.twitter.sdk.android.core.TwitterSession;
import retrofit.http.GET;
import retrofit.http.Query;
public class MyTwitterApiClient extends TwitterApiClient {
public MyTwitterApiClient(TwitterSession session) {
super(session);
}
public CustomService getCustomService() {
return getService(CustomService.class);
}
interface CustomService {
#GET("/1.1/followers/ids.json")
void show(#Query("user_id") long id);
}
}
I think when i send an id ,service brings followers ids.
MyTwitterApiClient aa = new MyTwitterApiClient(session);
aa.getCustomService().show(userId);
But app is stopped.What is my wrong ?
LogCat is
5897-15897/com.tumymedia.tumer.lylafortwitter E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.tumymedia.tumer.lylafortwitter, PID: 15897
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=140, result=-1, data=Intent { (has extras) }} to activity {com.tumymedia.tumer.lylafortwitter/com.tumymedia.tumer.lylafortwitter.MainActivity}: java.lang.IllegalArgumentException: CustomService.show: Must have either a return type or Callback as last argument.
at android.app.ActivityThread.deliverResults(ActivityThread.java:4058)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4101)
at android.app.ActivityThread.access$1400(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1497)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5942)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
Caused by: java.lang.IllegalArgumentException: CustomService.show: Must have either a return type or Callback as last argument.
at retrofit.RestMethodInfo.methodError(RestMethodInfo.java:123)
at retrofit.RestMethodInfo.parseResponseType(RestMethodInfo.java:285)
at retrofit.RestMethodInfo.<init>(RestMethodInfo.java:113)
at retrofit.RestAdapter.getMethodInfo(RestAdapter.java:213)
at retrofit.RestAdapter$RestHandler.invoke(RestAdapter.java:236)
at java.lang.reflect.Proxy.invoke(Proxy.java:397)
at com.tumymedia.tumer.lylafortwitter.$Proxy16.show(Unknown Source)
at com.tumymedia.tumer.lylafortwitter.MainActivity$1.success(MainActivity.java:55)
at com.twitter.sdk.android.core.identity.TwitterAuthClient$CallbackWrapper.success(TwitterAuthClient.java:230)
at com.twitter.sdk.android.core.Callback.success(Callback.java:40)
at com.twitter.sdk.android.core.identity.AuthHandler.handleOnActivityResult(AuthHandler.java:91)
at com.twitter.sdk.android.core.identity.TwitterAuthClient.onActivityResult(TwitterAuthClient.java:161)
at com.twitter.sdk.android.core.identity.TwitterLoginButton.onActivityResult(TwitterLoginButton.java:131)
at com.tumymedia.tumer.lylafortwitter.MainActivity.onActivityResult(MainActivity.java:96)
at android.app.Activity.dispatchActivityResult(Activity.java:6543)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4054)
            at android.app.ActivityThread.handleSendResult(ActivityThread.java:4101)
            at android.app.ActivityThread.access$1400(ActivityThread.java:177)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1497)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:145)
            at android.app.ActivityThread.main(ActivityThread.java:5942)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)

Actually Fabric uses retrofit to make REST Api calls and as mentioned
in Fabric documentation, for getting ids of followers we need to pass
user_id as parameter and retrieve list in response.
MyTwitterApiClient.java
import com.twitter.sdk.android.core.Callback;
import com.twitter.sdk.android.core.TwitterApiClient;
import com.twitter.sdk.android.core.TwitterSession;
import retrofit.client.Response;
import retrofit.http.GET;
import retrofit.http.Query;
public class MyTwitterApiClient extends TwitterApiClient {
public MyTwitterApiClient(TwitterSession session) {
super(session);
}
/**
* Provide CustomService with defined endpoints
*/
public CustomService getCustomService() {
return getService(CustomService.class);
}
}
// example users/show service endpoint
interface CustomService {
#GET("/1.1/followers/ids.json")
void list(#Query("user_id") long id, Callback<Response> cb);
}
Now in MainActivity we will authenticate the user and then by getting
the session we will retrieve the list of all followers corresponding
to a userid.
MainActivity.java
public class MainActivity extends AppCompatActivity {
// Note: Your consumer key and secret should be obfuscated in your source code before shipping.
private static final String TWITTER_KEY = "YOUR_TWITTER_KEY";
private static final String TWITTER_SECRET = "YOUR_TWITTER_SECRET";
TwitterLoginButton loginButton;
SharedPreferences shared;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET);
Fabric.with(this, new Twitter(authConfig), new Crashlytics());
setContentView(R.layout.activity_main);
shared = getSharedPreferences("demotwitter", Context.MODE_PRIVATE);
loginButton = (TwitterLoginButton) findViewById(R.id.login_button);
loginButton.setCallback(new Callback<TwitterSession>() {
#Override
public void success(Result<TwitterSession> result) {
// Do something with result, which provides a TwitterSession for making API calls
TwitterSession session = Twitter.getSessionManager()
.getActiveSession();
TwitterAuthToken authToken = session.getAuthToken();
String token = authToken.token;
String secret = authToken.secret;
//Here we get all the details of user's twitter account
System.out.println(result.data.getUserName()
+ result.data.getUserId());
Twitter.getApiClient(session).getAccountService()
.verifyCredentials(true, false, new Callback<User>() {
#Override
public void success(Result<User> userResult) {
User user = userResult.data;
//Here we get image url which can be used to set as image wherever required.
System.out.println(user.profileImageUrl+" "+user.email+""+user.followersCount);
}
#Override
public void failure(TwitterException e) {
}
});
shared.edit().putString("tweetToken", token).commit();
shared.edit().putString("tweetSecret", secret).commit();
TwitterAuthClient authClient = new TwitterAuthClient();
authClient.requestEmail(session, new Callback<String>() {
#Override
public void success(Result<String> result) {
// Do something with the result, which provides the
// email address
System.out.println(result.toString());
Log.d("Result", result.toString());
Toast.makeText(getApplicationContext(), result.data,
Toast.LENGTH_LONG).show();
}
#Override
public void failure(TwitterException exception) {
// Do something on failure
System.out.println(exception.getMessage());
}
});
MyTwitterApiClient apiclients=new MyTwitterApiClient(session);
apiclients.getCustomService().list(result.data.getUserId(), new Callback<Response>() {
#Override
public void failure(TwitterException arg0) {
// TODO Auto-generated method stub
}
#Override
public void success(Result<Response> arg0) {
// TODO Auto-generated method stub
BufferedReader reader = null;
StringBuilder sb = new StringBuilder();
try {
reader = new BufferedReader(new InputStreamReader(arg0.response.getBody().in()));
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
String result = sb.toString();
System.out.println("Response is>>>>>>>>>"+result);
try {
JSONObject obj=new JSONObject(result);
JSONArray ids=obj.getJSONArray("ids");
//This is where we get ids of followers
for(int i=0;i<ids.length();i++){
System.out.println("Id of user "+(i+1)+" is "+ids.get(i));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
#Override
public void failure(TwitterException exception) {
// Do something on failure
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Pass the activity result to the login button.
loginButton.onActivityResult(requestCode, resultCode, data);
}
}

In Retrofit 2.0,
Interface ->
public interface FollowersService {
#GET("/1.1/followers/list.json")
Call<ResponseBody> list(#Query("screen_name") String userId);
}
Call to method ->
FollowersService followersService = followersTwitterApiClient.getFollowersService();
Call<ResponseBody> call = followersService.list(userId);
call.enqueue(followerCallback);
Custom Api client ->
public class FollowersTwitterApiClient extends TwitterApiClient {
public FollowersTwitterApiClient(TwitterSession twitterSession){
super(twitterSession);
}
public FollowersService getFollowersService(){
return getService(FollowersService.class);
}
}

You need to authenticate to Twitter in order to be able to call the API and get results. I don't see that happening in this code. (Maybe you are doing it outside this code?)
Details on Twitter authentication at https://dev.twitter.com/oauth

Related

org.json.JSONException: No value for error_status

Iam using easebuzz payment gateway and it was working fine two days ago, but now
I got stuck in payments and im getting an error but easebuzz is not showing any error its in the screen of Transaction is Processing...
after selecting payment option(ex: Bank) it will process the payment and next it is redirecting to Transaction processing page and it got stuck in there after waiting for long time still its not showing any response but only a error log in the terminal. it was working fine few days before i didnt changed any payment code.ihave Updated the flutter version but i dont thing flutter version cant do anything because My previous projects that built few months before also not working due to this issue in the easebuzz ,
error log
W/System.err(30454): org.json.JSONException: No value for error_status W/System.err(30454): at org.json.JSONObject.get(JSONObject.java:399) W/System.err(30454): at org.json.JSONObject.getString(JSONObject.java:560) W/System.err(30454): at com.easebuzz.payment.kit.PWEBankPageActivity$PWEPaymentStatus$1.run(PWEBankPageActivity.java:1016) W/System.err(30454): at android.os.Handler.handleCallback(Handler.java:883) W/System.err(30454): at android.os.Handler.dispatchMessage(Handler.java:100) W/System.err(30454): at android.os.Looper.loop(Looper.java:224) W/System.err(30454): at android.app.ActivityThread.main(ActivityThread.java:7590) W/System.err(30454): at java.lang.reflect.Method.invoke(Native Method) W/System.err(30454): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539) W/System.err(30454): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
This is the Javacode that is given by easebuzz
MainActivity.java
public class MainActivity extends FlutterActivity {
private static final String CHANNEL = "easebuzz";
MethodChannel.Result channel_result;
boolean start_payment = true;
#Override
public void configureFlutterEngine(#NonNull FlutterEngine flutterEngine) {
GeneratedPluginRegistrant.registerWith(flutterEngine);
start_payment = true;
new MethodChannel(getFlutterEngine().getDartExecutor().getBinaryMessenger(), CHANNEL).setMethodCallHandler(
new MethodChannel.MethodCallHandler() {
#Override
public void onMethodCall(MethodCall call, MethodChannel.Result result) {
channel_result = result;
if (call.method.equals("payWithEasebuzz")) {
if (start_payment) {
start_payment = false;
startPayment(call.arguments);
}
}
}
});
}
private void startPayment(Object arguments) {
try {
System.out.print(":::::::::::::Payment started 0::::::::::::::");
Gson gson = new Gson();
System.out.print(":::::::::::::Payment started 1::::::::::::::");
JSONObject parameters = new JSONObject(gson.toJson(arguments));
System.out.print(":::::::::::::Payment started ::::::::::::::");
Intent intentProceed = new Intent(getBaseContext(), PWECouponsActivity.class);
intentProceed.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
intentProceed.putExtra("access_key", parameters.getString("access_key"));
intentProceed.putExtra("pay_mode", parameters.getString("pay_mode"));
startActivityForResult(intentProceed, PWEStaticDataModel.PWE_REQUEST_CODE);
} catch (Exception e) {
start_payment = true;
Map error_map = new HashMap<>();
Map error_desc_map = new HashMap<>();
String error_desc = "exception occured:" + e.getMessage();
error_desc_map.put("error", "Exception");
error_desc_map.put("error_msg", error_desc);
error_map.put("result", PWEStaticDataModel.TXN_FAILED_CODE);
error_map.put("payment_response", error_desc_map);
channel_result.success(error_map);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
if (requestCode == PWEStaticDataModel.PWE_REQUEST_CODE) {
start_payment = true;
JSONObject response = new JSONObject();
Map error_map = new HashMap<>();
if (data != null) {
String result = data.getStringExtra("result");
String payment_response = data.getStringExtra("payment_response");
System.out.print(":::::::::::::Payment response ::::::::::::::");
System.out.print(payment_response);
try {
JSONObject obj = new JSONObject(payment_response);
response.put("result", result);
response.put("payment_response", obj);
channel_result.success(JsonConverter.convertToMap(response));
} catch (Exception e) {
Map error_desc_map = new HashMap<>();
error_desc_map.put("error", result);
error_desc_map.put("error_msg", payment_response);
error_map.put("result", result);
error_map.put("payment_response", error_desc_map);
channel_result.success(error_map);
}
} else {
Map error_desc_map = new HashMap<>();
String error_desc = "Empty payment response";
error_desc_map.put("error", "Empty error");
error_desc_map.put("error_msg", error_desc);
error_map.put("result", "payment_failed");
error_map.put("payment_response", error_desc_map);
channel_result.success(error_map);
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
}

problem with android : data from class don't send to activity

i wrote the code to an activity it work perfect but when i writhing them to a java class and send the result to the activity is not show anything to text view.
public class TheaudiodbWebData {
private String result = "";
public String getResult() {
return result;
}
public TheaudiodbWebData() {
getBiographyData();
}
private void getBiographyData() {
String url = "https://www.theaudiodb.com/api/v1/json/1/search.php?s=coldplay";
AsyncHttpClient client = new AsyncHttpClient();
client.get(url, new TextHttpResponseHandler() {
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
}
#Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
parseBiographyData(responseString);
}
});
}
private void parseBiographyData(String response) {
try {
Gson gson = new Gson();
TheaudiodbArtistBio bio = gson.fromJson(response, TheaudiodbArtistBio.class);
result = bio.getArtists().get(0).getStrArtist();
} catch (Exception e) {
}
}
}
and this is the Activity code :
public class BiographyActivity extends AppCompatActivity {
TextView test;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_biography);
test=findViewById(R.id.test);
TheaudiodbWebData bio=new TheaudiodbWebData();
test.setText(bio.getResult());
}
}
If you are not passing data from one Activity to another Activity and you are getting the result than problem is clear. Part of code which you are executing in onCreate() method:
TheaudiodbWebData bio=new TheaudiodbWebData();
test.setText(bio.getResult());
is executed immediately but you are getting results over the Internet which means that data is not received immediately (connecting server -> getting result -> returning result = takes some time) that is why you have callback methods onFailure and onSuccess which are triggered after result is returned from the Internet depending was it successful or fail.
So solution is to create your own interface with method where you can pass the result than implement that interface and create your own callback methods.
Or more simpler solution move this part of code directly into your Activity and set the the result to the TextView in onSucces method for example:
private void getBiographyData() {
String url = "https://www.theaudiodb.com/api/v1/json/1/search.php?s=coldplay";
AsyncHttpClient client = new AsyncHttpClient();
client.get(url, new TextHttpResponseHandler() {
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
}
#Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
test.setText(responseString);
}
});
}
After that simply call this method inside onCreate() like:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_biography);
test=findViewById(R.id.test);
getBiographyData();
}

Android: Retrofit 2 get JSON value from XML

I'm using Retrofit 2.1.0. The return in XML is quite different. The JSON was placed inside the XML. I have searching about this for several hours but still not getting any idea how to retrieve the JSON value.
XML :
<string xmlns="http://www.something.com/">
[{"ReturnOK":"OK","Fullname":"Micheal","Userid":"4","strAppID":"9A380FFEACC444E8BE1E616F72A573C0","Phoneno":"1234567890"}]
</string>
Retrofit Client:
public static Retrofit getManager() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(Constants.HTTP.BASE_URL)
.client(new OkHttpClient())
.addConverterFactory(SimpleXmlConverterFactory.create())
.build();
}
return retrofit;
}
Login Interface:
public interface LoginService {
#GET(Constants.LOGIN.LOGIN_URL)
Call<XMLString> doLogin(#Query(Constants.LOGIN.strAppID) String strAppID,
#Query(Constants.LOGIN.uname) String uname,
#Query(Constants.LOGIN.upassword) String upassword);
}
XMLString :
#Root(name="string", strict = false)
public class XMLString {
private String reponse;
public String getReponse() {
return reponse;
}
public void setReponse(String reponse) {
this.reponse = reponse;
}
}
Method :
private void loginProcess(String username, String password){
LoginService endPoints = mManager.getManager().create(LoginService.class);
Call<XMLString> call = endPoints.doLogin("1", username, password);
call.enqueue(new Callback<XMLString>() {
#Override
public void onResponse(Call<XMLString> call, Response<XMLString> response) {
if (response.isSuccessful()) {
XMLString xmlString = null;
try {
xmlString = call.execute().body();
} catch (IOException e) {
e.printStackTrace();
}
XMLString FromResponse = response.body();
Toast.makeText(getActivity(), FromResponse.toString(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<XMLString> call, Throwable t) {
Utils.T(getActivity(), t.getMessage().toString());
}
});
}
Error :
FATAL EXCEPTION: main
Process: app.test.com.junn, PID: 12501
java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableCollection.add(Collections.java:1128)
at app.test.com.junn.controller.RestManager.getManager(RestManager.java:29)
at app.test.com.junn.ui.fragment.LoginDialogFragment.loginProcess(LoginDialogFragment.java:100)
at app.test.com.junn.ui.fragment.LoginDialogFragment.onClick(LoginDialogFragment.java:83)
at android.view.View.performClick(View.java:5610)
at android.view.View$PerformClick.run(View.java:22265)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
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)
Any help is really appreciated.

Getting null object reference If i start 2nd activity before 3rd activity (No error if I move from 1st to 3rd directly)

I know its a common error , and i know lots of topics here were asking about the same error, but i tried alot of solutions and non works.
My application is like this:
1st activity is a sign in activity,
2nd is a menu to navigate where to go,
3rd is the customer's details.
I think i know where the problem is but i don't whats causing it
In the 2nd activity i am calling a function to get the customer id (the same function i am calling in the 3rd activity but without taking all the details i am only taking it's ID because i need it in other activities )
So result i am getting second time is always null , which is causing this error
so if i jump directly from 1st to 3rd app doesn't crash.
but (1st 2nd 3rd ) then the function will be called twice (even though i am storing data in a different object) and works only at the first time it's called
Hope i explained it well
now my code for 2nd activity:
public class AfterLogin extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new AsyncpkAbone().execute(SharedValues.AboneKod);
setContentView(R.layout.activity_after_login);
}
public void AboneBilgiPressed(View v){
Intent i = new Intent(AfterLogin.this, UserDetailsActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
}
protected class AsyncpkAbone extends AsyncTask<String,Void,UserDetailsTable>
{
#Override
protected UserDetailsTable doInBackground(String... params) {
// TODO Auto-generated method stub
UserDetailsTable userDetail2=null;
RestAPI api = new RestAPI();
try {
JSONObject jsonObj = api.GetUserDetails(params[0]);
JSONParser parser = new JSONParser();
userDetail2 = parser.parseUserDetails(jsonObj);
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("AsyncUserDetails", e.getMessage());
}
return userDetail2;
}
#Override
protected void onPostExecute(UserDetailsTable result2) {
// TODO Auto-generated method stub
SharedValues.AboneKod =result2.getAboneKod();
SharedValues.pkAbone = result2.getPkAbone();
}
}
the Code for the 3rd activity (user details)
public class UserDetailsActivity extends AppCompatActivity {
TextView tvAdres, tvTelefon,tvpkAbone;
String Adres;
String WEBParola;
String Tel1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_details);
new AsyncUserDetails().execute(SharedValues.AboneKod);
tvAdres = (TextView) findViewById(R.id.tv_firstname);
tvAdres.setTextIsSelectable(true);
tvTelefon = (TextView) findViewById(R.id.tv_lastname);
tvTelefon.setTextIsSelectable(true);
tvpkAbone = (TextView) findViewById(R.id.tv_pkAbone);
tvpkAbone.setTextIsSelectable(true);
tvAdres.setText(Adres);
tvTelefon.setText(Tel1);
tvpkAbone.setText(String.valueOf( SharedValues.pkAbone));
}
protected class AsyncUserDetails extends AsyncTask<String,Void,UserDetailsTable>
{
#Override
protected UserDetailsTable doInBackground(String... params) {
// TODO Auto-generated method stub
UserDetailsTable userDetail=null;
RestAPI api = new RestAPI();
try {
JSONObject jsonObj = api.GetUserDetails(params[0]);
JSONParser parser = new JSONParser();
userDetail = parser.parseUserDetails(jsonObj);
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("AsyncUserDetails", e.getMessage());
}
return userDetail;
}
#Override
protected void onPostExecute(UserDetailsTable result) {
// TODO Auto-generated method stub
tvAdres.setText(result.getAdres());
tvTelefon.setText(result.getTelefon());
}
}
the data i get from the function is stored in a object of type (userdetails tables)
the code for the Userdetailstable is (might be needed)
package com.artyazilim.art;
public class UserDetailsTable {
String Adres,Tel1,AboneKod,WEBParola;
int pkAbone;
public UserDetailsTable(String Adres, String Tel1, String AboneKod,
String WEBParola,int pkAbone) {
super();
this.Adres = Adres;
this.Tel1 = Tel1;
this.AboneKod = AboneKod;
this.WEBParola = WEBParola;
this.pkAbone = pkAbone;
}
public UserDetailsTable() {
super();
this.Adres = null;
this.Tel1 = null;
this.AboneKod = null;
this.WEBParola = null;
this.pkAbone = 0;
}
public String getAdres() {
return Adres;
}
public void setAdres(String adres) {
Adres = adres;
}
public String getTelefon() {
return Tel1;
}
public void setTelefon(String telefon) {
Tel1 = telefon;
}
public String getAboneKod() {
return AboneKod;
}
public void setAboneKod(String aboneKod) {
AboneKod = aboneKod;
}
public String getWEBParola() {
return WEBParola;
}
public void setWEBParola(String WEBParola) {
this.WEBParola = WEBParola;
}
public int getPkAbone() {
return pkAbone;
}
public void setPkAbone(int pkAbone) {
this.pkAbone = pkAbone;
}
}
the function which i am calling in the both Async is this:
public JSONObject GetUserDetails(String AboneKod) throws Exception {
JSONObject result = null;
JSONObject o = new JSONObject();
JSONObject p = new JSONObject();
o.put("interface","Service1");
o.put("method", "GetUserDetails");
p.put("AboneKod",mapObject(AboneKod));
o.put("parameters", p);
String s = o.toString();
String r = load(s);
result = new JSONObject(r);
return result;
}
and in the web service this is the GetUserDetails function:
public DataTable GetUserDetails(string AboneKod)
{
DataTable userDetailsTable = new DataTable();
userDetailsTable.Columns.Add(new DataColumn("Adres", typeof(String)));
userDetailsTable.Columns.Add(new DataColumn("Tel1", typeof(String)));
userDetailsTable.Columns.Add(new DataColumn("pkAbone", typeof(String)));
if (dbConnection.State.ToString() == "Closed")
{
dbConnection.Open();
}
string query = "SELECT Adres,Tel1,pkAbone FROM r_Abone WHERE AboneKod='" + AboneKod + "';";
SqlCommand command = new SqlCommand(query, dbConnection);
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
userDetailsTable.Rows.Add(reader["Adres"], reader["Tel1"], reader["pkAbone"]);
}
}
reader.Close();
dbConnection.Close();
return userDetailsTable;
}
the error i am getting when going from 2nd to 3rd is
java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.String com.artyazilim.art.UserDetailsTable.getAdres()' on a
null object reference
10-30 05:33:13.410 24881-24881/com.artyazilim.art E/AndroidRuntime:
at
com.artyazilim.art.UserDetailsActivity$AsyncUserDetails.onPostExecute(UserDetailsActivity.java:74)
10-30 05:33:13.410 24881-24881/com.artyazilim.art E/AndroidRuntime:
at
com.artyazilim.art.UserDetailsActivity$AsyncUserDetails.onPostExecute(UserDetailsActivity.java:47)
10
i know it seems like a duplicate and I know the rules search before ask,I have spent lots of time trying other's solutions but the reason i might didn't find the answer else where is because i don't know whats is actually causing this error so not knowing what to search for.
thanks in advance :)
In you second activity check if result2.getAboneKod(); is not returning a null object.
I think this is why when you open the 3rd activity from the 2nd, you have the NullPointerException.

Accessing property that is filled by an AsyncTask returns null

I am trying to get values from my User class (holding all the user information for the logged in user.
It is set once logged in, and it is printing out in the log just fine, but then when calling from the class that instantiates it, it returns a null? Here is the code:
public ApiConnector api;
public String ID;
public String USERNAME = null;
public String NAME = null;
public String LASTNAME = null;
public String PASSWORD = null;
public String EMAIL = null;
public User(String id) {
this.ID = id;
this.api = new ApiConnector();
new GetUserDataClass().execute(api);
}
private class GetUserDataClass extends AsyncTask<ApiConnector,Boolean,JSONArray> {
#Override
protected JSONArray doInBackground(ApiConnector... params) {
return params[0].getAllUserData(ID);
}
#Override
protected void onPostExecute(JSONArray jsonArray) {
if(jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = null;
try {
json = new JSONObject();
json = jsonArray.getJSONObject(i);
if(!json.getString("username").isEmpty()) {
setUsername(json.getString("username"));
Log.d("username", getUsername());
}
if(!json.getString("firstname").isEmpty()) {
setName(json.getString("firstname"));
Log.d("name", getName());
}
if(!json.getString("lastname").isEmpty()) {
setLastName(json.getString("lastname"));
Log.d("lastname", getLastName());
}
if(!json.getString("email").isEmpty()) {
setEmail(json.getString("email"));
Log.d("email", getEmail());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} else {
Log.d("hey", "hey");
}
}
The logcat output is:
05-19 02:03:55.996: W/EGL_emulation(4367): eglSurfaceAttrib not implemented
05-19 02:03:55.996: D/username(4367): Me
05-19 02:03:55.996: D/name(4367): Me
05-19 02:03:55.996: D/lastname(4367): Mememe
05-19 02:03:55.996: D/email(4367): me#example.com
I have all appropriate getters and setters in the class (as you can see in the above code, working fine.
Here is the Menu class (that is returning the null):
public class Menu extends Activity {
private String ID;
private User user;
public TextView tvusername;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
init();
}
public void init() {
Bundle bundle = getIntent().getExtras();
ID = bundle.getString("id");
user = new User(ID);
tvusername = (TextView) findViewById(R.id.tvUsername);
tvusername.setText(ID + " " + user.getEmail());
}
}
Here is what it looks like on the emulator:
I have spent the last day and a half looking for solutions, but came up empty. Please would you help?
you can use
new GetUserDataClass().execute(api).get();
so that system will wait to complete AsyncTask. and you will get the id.
You are loading user data in an AsyncTask... and that's good because it seems to perform some network operation.
It means that user data loading is performed asynchronously... and so not available immediately.
You have a callback onPostExecute in the AsyncTask : use it to update the UI with something like this code :
//you need to initialize it in the AsyncTask constrtuctor
final Activity myActivity;
#Override
protected void onPostExecute(JSONArray jsonArray) {
//json parsing code
//...
//and finally update the UI
new Handler(Looper.getMainLooper()).post(
new Runnable(){
public void run(){
TextView tvusername = (TextView) myActivity.findViewById(R.id.tvUsername);
tvusername.setText(ID + " " + getEmail());
}
}
);
}
I think you forgot to use static word in User class object creation while setting data.
other wise it will create new instance every time and that object will not show your data.
I solved it by using the Singleton Design Pattern in my User class. Just so people can look that up to solve this if they are having the same issues!
Cheers and thanks for all the replies!

Categories

Resources