AsyncTask HttpConnection in Android - android-asynctask

I want to create httpconnection using asyntask.three parameters are posted to the server
username,password and a search item.the search is provided by the user in an EditText such so that when the user clicks a button,the search item is sent to the server.I want to execute the doInbackground() method in the OnclickListener and display the response from the server on listviews.This is the AsyncTask Class
public class PostToServer extends AsyncTask<String, Void, String> {
#Override
protected void onPostExecute(String result) {
}
#Override
protected String doInBackground(String... arg0) {
try {
HttpClient client = new DefaultHttpClient();
String postURL = "url";
String username ="username";
String password = "password";
HttpPost post = new HttpPost(postURL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user", username));
params.add(new BasicNameValuePair("pass", password));
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
post.setEntity(ent);
HttpResponse responsePOST = client.execute(post);
HttpEntity resEntity = responsePOST.getEntity();
if (resEntity != null) {
Log.i("RESPONSE",EntityUtils.toString(resEntity));
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
This the class where the click event is called
public class StartPost extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result_page);
}
Button Submit = (Button) findViewById(R.id.btn_search);
EditText textvalue = (EditText)findViewById(R.id.searcheditText);
String value = textvalue.getText().toString();
PostToServer post = new PostToServer();
CheckInternetConnection check = new CheckInternetConnection(null);
private OnClickListener click = new OnClickListener() {
#Override
public void onClick(final View v) {
switch(v.getId()){
case R.id.btn_search:
post.execute();
break;
}
}
};
}
Questions
1.What am I doing wrong because it seems the post is not working and How can I display the server results from the onPostExecute()?
Thank You.

Create a onPostExecute method to display the results on your textview.
protected onPostExecute (String result){
TextView tv = (TextView) findViewById(R.id.textview1);
if(result != null){
tv.setText(result);
}
}

Related

How to change targetSdkVersion

I am having an issue with target targetSdkVersion.I want to move from 27 to 29 but when change to sdk 29 the app runs but does not display videos.But it displays the videos when it is sdk 27 or less.
Please can someone help me fix this.
/**
* A simple {#link Fragment} subclass.
*/
public class ChannelFragment extends Fragment {
private static String GOOGLE_YOUTUBE_API_KEY = "AIzaSyBJQYpQRTzM5wuuhMUxmP7rvP3lbMGtUZ8";//here you should use your api key for testing purpose you can use this api also
private static String CHANNEL_ID = "UCB_ZwuWCAuB7y0B93qvnkWw"; //here you should use your channel id for testing purpose you can use this api also
private static String CHANNLE_GET_URL = "https://www.googleapis.com/youtube/v3/search?part=snippet&order=date&channelId=" + CHANNEL_ID + "&maxResults=50&key=" + GOOGLE_YOUTUBE_API_KEY + "";
private RecyclerView mList_videos = null;
private VideoPostAdapter adapter = null;
private ArrayList<YoutubeDataModel> mListData = new ArrayList<>();
public ChannelFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_channel, container, false);
mList_videos = (RecyclerView) view.findViewById(R.id.mList_videos);
initList(mListData);
new RequestYoutubeAPI().execute();
return view;
}
private void initList(ArrayList<YoutubeDataModel> mListData) {
mList_videos.setLayoutManager(new LinearLayoutManager(getActivity()));
adapter = new VideoPostAdapter(getActivity(), mListData, new OnItemClickListener() {
#Override
public void onItemClick(YoutubeDataModel item) {
YoutubeDataModel youtubeDataModel = item;
Intent intent = new Intent(getActivity(), DetailsActivity.class);
intent.putExtra(YoutubeDataModel.class.toString(), youtubeDataModel);
startActivity(intent);
}
});
mList_videos.setAdapter(adapter);
}
//create an asynctask to get all the data from youtube
private class RequestYoutubeAPI extends AsyncTask<Void, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(CHANNLE_GET_URL);
Log.e("URL", CHANNLE_GET_URL);
try {
HttpResponse response = httpClient.execute(httpGet);
HttpEntity httpEntity = response.getEntity();
String json = EntityUtils.toString(httpEntity);
return json;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
if (response != null) {
try {
JSONObject jsonObject = new JSONObject(response);
Log.e("response", jsonObject.toString());
mListData = parseVideoListFromResponse(jsonObject);
initList(mListData);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
public ArrayList<YoutubeDataModel> parseVideoListFromResponse(JSONObject jsonObject) {
ArrayList<YoutubeDataModel> mList = new ArrayList<>();
if (jsonObject.has("items")) {
try {
JSONArray jsonArray = jsonObject.getJSONArray("items");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
if (json.has("id")) {
JSONObject jsonID = json.getJSONObject("id");
String video_id = "";
if (jsonID.has("videoId")) {
video_id = jsonID.getString("videoId");
}
if (jsonID.has("kind")) {
if (jsonID.getString("kind").equals("youtube#video")) {
YoutubeDataModel youtubeObject = new YoutubeDataModel();
JSONObject jsonSnippet = json.getJSONObject("snippet");
String title = jsonSnippet.getString("title");
String description = jsonSnippet.getString("description");
String publishedAt = jsonSnippet.getString("publishedAt");
String thumbnail = jsonSnippet.getJSONObject("thumbnails").getJSONObject("high").getString("url");
youtubeObject.setTitle(title);
youtubeObject.setDescription(description);
youtubeObject.setPublishedAt(publishedAt);
youtubeObject.setThumbnail(thumbnail);
youtubeObject.setVideo_id(video_id);
mList.add(youtubeObject);
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return mList;
}
}

kryonet client, send message to server without open a new connection

I'm saying i'm not a programmer but a guy who has been learning to program with java for a while. I hope to find the solution to my problem here. I'm trying to program my home automation system and remote control and to do this, I chose to use Kryonet. My problem is that every time I send the data to the server, the client opens a new connection. It's been 3 weeks since googlo and I try to figure out how to do it but with no results.
Every help is seriously appreciated. This is my code. Thank you.
This code work in my home network.
Sorry for my english...
public class MainActivity extends AppCompatActivity {
Button button;
String IP = "";
EditText editText;
TextView textView;
EditText editText3;
public static String msg_response;
public static String msg_request;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Handler handler = new MyHandler();
button = (Button) findViewById(R.id.button);
editText = (EditText) findViewById(R.id.editText);
editText3 = (EditText) findViewById(R.id.editText3);
textView = (TextView) findViewById(R.id.textView);
int MY_PERMISSIONS_REQUEST_INTERNET = 1;
int MY_PERMISSIONS_REQUEST_ACCESS_NETWORK_STATE = 1;
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.INTERNET},
MY_PERMISSIONS_REQUEST_INTERNET);
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_NETWORK_STATE},
MY_PERMISSIONS_REQUEST_ACCESS_NETWORK_STATE);
int MY_PERMISSIONS_REQUEST_ACCESS_WIFY_STATE = 1;
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_WIFI_STATE},
MY_PERMISSIONS_REQUEST_ACCESS_WIFY_STATE);
textView.setText(msg_response);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
msg_request = valueOf(editText3.getText().toString());
} catch (Exception e) {
e.printStackTrace();
}
MyThread myThread = new MyThread(handler);
myThread.start();
}
});
}
private class MyHandler extends Handler {
#Override
public void handleMessage(Message msg) {
Bundle bundle = msg.getData();
if (bundle.containsKey("msg da server")) {
String msgin = bundle.getString("msg da server");
textView.setText(msgin);
}
}
}
class MyThread extends Thread {
private Handler handler;
public MyThread(Handler handler) {
this.handler = handler;
}
public void run() {
System.out.println("MyThread running");
Client client = new Client();
client.start();
Kryo kryoClient = client.getKryo();
kryoClient.register(SampleRequest.class);
kryoClient.register(SampleResponse.class);
try {
client.connect(5000, "192.168.0.101", 54555, 54666);
} catch (IOException e) {
e.printStackTrace();
}
client.addListener(new Listener() {
public void received(Connection connection, Object object) {
if (object instanceof SampleResponse) {
SampleResponse response = (SampleResponse) object;
System.out.println(response.text);
msg_response = response.text.toString();
invia_activity(msg_response);
}
}
});
SampleRequest request = new SampleRequest();
request.text = msg_request;
client.sendTCP(request);
}
private void invia_activity(String invia) {
Message msg = handler.obtainMessage();
Bundle b = new Bundle();
b.putString("msg da server", "" + invia);
msg.setData(b);
handler.sendMessage(msg);
}
}
}
I dont have an direct solution, but i have an tutorial for it. I used the same one. So there the connections keeps open, and you can send as many packets as you need. Its without audio, but the code works well. After that you can experiment with the code. It works fine for me. This is the tutorial
I hope i can help you with this.
EDIT:
Maybe you can make an
public static Connection conn;
and you could use that object again and again as your connection to the server.

Unable to access response data out of VolleyRequest, attempted callbacks

I have tried using callback similar to my fragments and other people suggestion on callbacks, However I've had no luck i could be doing the callbacks wrong. The Toast inside the onResponse method of JsonArrayRequest returns an array size of 2. But i get 0 on the toast outside of the request. consignment.class implements parcelable
public class BackgroundTask{
String json_url;
Gson gson;
Type listType;
ProgressDialog pDialog;
ArrayList<Consignment> arrayList = new ArrayList<>();
AppController appController;
ConsAdapter adapter;
Context context;
public BackgroundTask(Context context){
this.context = context;
listType = new TypeToken<List<Consignment>>(){}.getType();
appController = AppController.getInstance();
gson = new Gson();
}
public void getAllCons(final GetAllConsListener callBack) {
String tag_json_obj = "json_obj_req";
//showProgressDialog();
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, json_url,null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
callBack.onSuccess(response.toString());
//hideProgressDialog();
Toast.makeText(context, "Consignments:"+arrayList.size(), Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(context, "Error...", Toast.LENGTH_SHORT).show();
error.printStackTrace();
//hideProgressDialog();
}
});
appController.addToRequestQueue(jsonArrayRequest);
}
Activity Class:
public class GetConsActivity extends AppCompatActivity {
RecyclerView recyclerView;
ConsAdapter adapter;
RecyclerView.LayoutManager layoutManager;
ArrayList<Consignment> arrayList;
TextView txtView;
BackgroundTask backgroundTask;
Type listType;
Gson gson;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_cons);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
gson = new Gson();
listType = new TypeToken<ArrayList<Consignment>>(){}.getType();
BackgroundTask backgroundTask = new BackgroundTask(GetConsActivity.this);
backgroundTask.getAllCons(new GetAllConsListener() {
#Override
public void onSuccess(String response) {
ArrayList<Consignment> list = parseResponse(response);
updateUI(list);
//Toast.makeText(GetConsActivity.this, "Consignments:"+arrayList.size(), Toast.LENGTH_LONG).show();
Log.d("ONSUCCESS", "ARRAYSIZE: "+arrayList.size());
}
});
}
public ArrayList<Consignment> parseResponse(String response){
ArrayList<Consignment> list = new ArrayList<>();
try {
JSONArray jsonArray = new JSONArray(response);
Log.d("PARSE", "parseResponse: "+jsonArray.length());
JSONObject jsonObject = jsonArray.getJSONObject(0);
for (int i = 0; i<jsonArray.length();i++){
Consignment con = null;
Log.d("PARSE", "parseID: "+jsonObject.getInt("conid"));
con.setConid(jsonObject.getInt("conid"));
Log.d("PARSE", "conID: "+con.getConid());
con.setDescription(jsonObject.getString("description"));
list.add(con);
}
Log.d("PARSED", "parsedResponse: "+list.size());
} catch (JSONException e) {
e.printStackTrace();
}
//arrayList =gson.fromJson(response,new TypeToken<ArrayList<Consignment>>(){}.getType());
//updateUI(arrayList);
return list;
}
public void updateUI(ArrayList<Consignment> consignments){
this.arrayList = consignments;
Log.d("UPDATE", "parseResponse: "+consignments.size());
if (adapter == null) {
adapter = new ConsAdapter(consignments,GetConsActivity.this);
recyclerView.setAdapter(adapter);
}else{
adapter.setConsignments(consignments);
adapter.notifyDataSetChanged();
}
}
Error:
D/mali_winsys: EGLint new_window_surface(egl_winsys_display*, void*, EGLSurface, EGLConfig, egl_winsys_surface**, egl_color_buffer_format*, EGLBoolean) returns 0x3000, [1440x2560]-format:1
E/RecyclerView: No adapter attached; skipping layout
I/qtaguid: Untagging socket 51
D/ViewRootImpl: MSG_RESIZED_REPORT: ci=Rect(0, 84 - 0, 0) vi=Rect(0, 84 - 0, 0) or=1
E/RecyclerView: No adapter attached; skipping layout
D/PARSE: parseResponse: 4
D/PARSE: parseID: 123456789
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.angel.createcon, PID: 26952
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.angel.createcon.Consignment.setConid(int)' on a null object reference
at com.angel.createcon.GetConsActivity.parseResponse(GetConsActivity.java:80)
at com.angel.createcon.GetConsActivity$2.onSuccess(GetConsActivity.java:56)
at com.angel.createcon.BackgroundTask$2.onResponse(BackgroundTask.java:50)
at com.angel.createcon.BackgroundTask$2.onResponse(BackgroundTask.java:47)
at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7331)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
I/Process: Sending signal. PID: 26952 SIG: 9
Application terminated.
So I'll take a stab at this - having the activity implement the listener that way is a bit strange, though I don't think that's the issue. I also don't understand why you chose to save the list type to a variable - I've not seen anyone do that before.
However, getting to your question about the toast and why it's 0 - If you're talking about the toast that comes after the getAllCons call -it's because that code is executed before the callback code. completes.
Try something like this and see what it does.
public class BackgroundTask{
String json_url;
Gson gson;
Type listType;
Context context;
public BackgroundTask(Context context){
this.context = context;
listType = new TypeToken<List<Consignment>>(){}.getType();
appController = AppController.getInstance();
gson = new Gson();
}
public void getAllCons(final GetAllConsListener callBack) {
String tag_json_obj = "json_obj_req";
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, json_url,null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
callBack.onSuccess(response.toString());
Toast.makeText(context, "Consignments:"+arrayList.size(), Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
appController.addToRequestQueue(jsonArrayRequest);
}
public class GetConsActivity extends AppCompatActivity {
RecyclerView recyclerView;
ConsAdapter adapter;
RecyclerView.LayoutManager layoutManager;
TextView txtView;
BackgroundTask backgroundTask;
Gson gson;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_cons);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
gson = new Gson();
BackgroundTask backgroundTask = new BackgroundTask(GetConsActivity.this);
backgroundTask.getAllCons(new GetAllConsListener() {
#Override
public void onSuccess(String response) {
List<Consignment> values = parseResponse(response);
updateUI(values);
}
});
//code may execute here but callback is not yet complete.
}
public List<Consignment> parseResponse(String response){
return gson.fromJson(response,listType);
}
private void updateUI(List<Consignment> consignments){
if(adapter == null){
adapter = new ConsAdapter(consignments)
recyclerView.setAdapter(adapter);
} else {
adapter.consignments = consignments;
adapter.notifyDataSetChanged();
}
}

Whatsapp implicit intent not working

I am trying to share image and text via whatsapp using implicit intent but I'm not able to share. I have searched the net but could not find any proper explanation. I have attached the code below.
... the code works without errors.but it dose not share content with whatsapp. i have searched all the places in google and on stackoverflow .but could not encounter with any proper explanation
public class MainActivity extends Activity implements View.OnClickListener {
TextView title_text,text_description;
ImageButton main_image;
Button button;
private static String url = "random url ";
private static final String TAG_ID = "title";
private static final String TAG_IMAGE = "image_url";
private static final String TAG_DESC = "product_desc";
String id;
String name;
String image;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text_description=(TextView)findViewById(R.id.text_description);
title_text=(TextView)findViewById(R.id.text_title);
main_image=(ImageButton)findViewById(R.id.image_main);
button= (Button) findViewById(R.id.button);
button.setOnClickListener(this);
new GetContacts().execute();
}
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"whatsappsharing",Toast.LENGTH_SHORT).show();
Intent whatsappintent=new Intent();
whatsappintent.setAction(Intent.ACTION_SEND);
Uri uri= Uri.parse(TAG_IMAGE);
whatsappintent.setType("text/plain");
whatsappintent.putExtra(Intent.EXTRA_TEXT, "hello nathar");
whatsappintent.setType("image/jpeg");
whatsappintent.putExtra(Intent.EXTRA_STREAM,uri);
whatsappintent.setPackage("com.whatsapp");
startActivity(whatsappintent);
}
private class GetContacts extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler sh = new ServiceHandler();
String jsonStr = sh.makeServiceCall(url, ServiceHandler.POST);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
id = jsonObj.getString(TAG_ID);
Log.d(TAG_ID,"title");
name = jsonObj.getString(TAG_DESC);
Log.d(TAG_DESC,"name");
image=jsonObj.getString(TAG_IMAGE);
Log.d(TAG_IMAGE,"image");
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (image!=null && !image.equalsIgnoreCase(""))
Picasso.with(MainActivity.this).load(image).fit().into(main_image);
title_text.setText(id);
text_description.setText(name);
}
}
}
Try this piece of code:
Uri imageUri = Uri.parse(TAG_IMAGE);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
// Target whatsapp:
shareIntent.setPackage("com.whatsapp");
// Add text and then Image URI
shareIntent.putExtra(Intent.EXTRA_TEXT, <Message_text>);
shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
try {
startActivity(shareIntent);
} catch (android.content.ActivityNotFoundException ex) {
ex.printStackTrace();
}
where Message_text will be sent as a image caption

java.lang.NullPointerException in textview inside asyncTask

If I use the following code, I will have no error, but there will be a freeze time.
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.profilepic);
initialize();
Bundle bundle = getIntent().getExtras();
email = bundle.getString("Email");
ArrayList<NameValuePair> postParameters;
String response = null;
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("emaillog", email));
try {
response = CustomHttpClient.executeHttpPost("http://whatstherex.info/checkU.php", postParameters);
res = response.toString();
res = res.replaceAll("null", "");
username = res.toString();
tvProfilePic.setText("Hi " + username + ", you are encourage to add a profile picture.");
}catch(Exception e){
res = e.toString();
tvProfilePic.setText(res);
}
}
But if I use this code with asyncTask and progressDialog like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.profilepic);
initialize();
getUsername();
}
private AsyncTask<String, Void, String> task;
public void getUsername(){
Bundle bundle = getIntent().getExtras();
email = bundle.getString("Email");
task = new AsyncTask<String, Void, String>() {
ProgressDialog dialog;
ArrayList<NameValuePair> postParameters;
String response = null;
#Override
protected void onPreExecute() {
//
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("emaillog", email));
dialog = new ProgressDialog(Profilepic.this, ProgressDialog.STYLE_SPINNER);
dialog.setMessage("Loading Data...");
dialog.show();
}
#Override
protected String doInBackground(String... params) {
//
try {
response = CustomHttpClient.executeHttpPost("http://whatstherex.info/checkU.php", postParameters);
res = response.toString();
res = res.replaceAll("null", "");
username = res.toString();
return username;
}catch(Exception e){
res = e.toString();
return res;
}
}
#Override
protected void onPostExecute(String result) {
if(result.length()< 25){
username = result;
tvProfilePic.setText("Hi " + result + ", you are encourage to add a profile picture.");
dialog.dismiss();
}else{
tvProfilePic.setText(result);
dialog.dismiss();
}
}
};
task.execute();
}
I get java.lang.NullPointerException in the textview.
What's the problem? Can anyone help me how to resolve this issue with NullPointerException appearing?
I see that you use tvProfilePic but I don't see where you define it.
In case you are not defining it, it should be done in a similar way as
tvProfilePic = findViewById(R.id.profile_pic)
Are you doing this?
Note that 'profile_pic' is the name in the layout XML document.
You are using tvProfilePic as a textview but i can't see where you defined it.
if you are not defining it then define it using something like
tvProfilePic = findViewById(R.id.profile_pic)
You are getting nullpointerexception because your tvProfilePic is null

Resources