How to implement json to android correct? - android

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.

Related

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

Error : method gettext() must be call from UI thread is worker

While working on a project I'm getting this error
Error : method gettext() must be call from UI thread is worker
on the following line :
String url = Util.send_chat_url+"?email_id="+editText_mail_id.getText().toString()+"&message="+editText_chat_message.getText().toString();
Please Help
This is my entire code for the class ChatActivity.java
package com.example.ankit.myapplication;
import android.app.Activity;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.example.ankit.myapplication.XmppService;
import com.squareup.okhttp.OkHttpClient;
import org.jivesoftware.smack.packet.Message;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Scanner;
//import services.XmppService;
public class ChatActivity extends Activity {
EditText editText_mail_id;
EditText editText_chat_message;
ListView listView_chat_messages;
Button button_send_chat;
List<ChatObject> chat_list;
BroadcastReceiver recieve_chat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
Scanner in = new Scanner(System.in);
XmppService xm= new XmppService();
Log.d("pavan","in chat "+getIntent().getStringExtra("user_id"));
Log.d("pavan","in chat server "+Util.SERVER);
XmppService.setupAndConnect(ChatActivity.this, Util.SERVER, "",
getIntent().getStringExtra("user_id"), Util.XMPP_PASSWORD);
editText_mail_id= (EditText) findViewById(R.id.editText_mail_id);
editText_chat_message= (EditText) findViewById(R.id.editText_chat_message);
listView_chat_messages= (ListView) findViewById(R.id.listView_chat_messages);
button_send_chat= (Button) findViewById(R.id.button_send_chat);
button_send_chat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// send chat message to server
String message=editText_chat_message.getText().toString();
showChat("sent",message);
// new SendMessage().execute();
XmppService.sendMessage(ChatActivity.this, editText_mail_id.getText().toString() + Util.SUFFIX_CHAT, Message.Type.chat, message);
editText_chat_message.setText("");
}
});
recieve_chat=new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String message=intent.getStringExtra("message");
Log.d("pavan","in local braod "+message);
showChat("recieve",message);
}
};
LocalBroadcastManager.getInstance(this).registerReceiver(recieve_chat, new IntentFilter("message_recieved"));
}
private void showChat(String type, String message){
if(chat_list==null || chat_list.size()==0){
chat_list= new ArrayList<ChatObject>();
}
chat_list.add(new ChatObject(message,type));
ChatAdabter chatAdabter=new ChatAdabter(ChatActivity.this,R.layout.chat_view,chat_list);
listView_chat_messages.setAdapter(chatAdabter);
//chatAdabter.notifyDataSetChanged();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
private class SendMessage extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String url = Util.send_chat_url+"?email_id="+editText_mail_id.getText().toString()+"&message="+editText_chat_message.getText().toString();
Log.i("pavan", "url" + url);
OkHttpClient client_for_getMyFriends = new OkHttpClient();
String response = null;
// String response=Utility.callhttpRequest(url);
try {
url = url.replace(" ", "%20");
response = callOkHttpRequest(new URL(url),
client_for_getMyFriends);
for (String subString : response.split("<script", 2)) {
response = subString;
break;
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//Toast.makeText(context,"response "+result,Toast.LENGTH_LONG).show();
}
}
// Http request using OkHttpClient
String callOkHttpRequest(URL url, OkHttpClient tempClient)
throws IOException {
HttpURLConnection connection = tempClient.open(url);
connection.setConnectTimeout(40000);
InputStream in = null;
try {
// Read the response.
in = connection.getInputStream();
byte[] response = readFully(in);
return new String(response, "UTF-8");
} finally {
if (in != null)
in.close();
}
}
byte[] readFully(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
for (int count; (count = in.read(buffer)) != -1;) {
out.write(buffer, 0, count);
}
return out.toByteArray();
}
}
Do not access the Android UI toolkit from outside the UI thread
Pass editText_mail_id.getText() and editText_chat_message.getText() as parameters to your async task or set it in onPreExecute to some variable
Like :
private class SendMessage extends AsyncTask<String, Void, String> {
private String mailId;
private String msgText;
#Override
protected void onPreExecute() {
super.onPreExecute();
mailId = editText_mail_id.getText().toString();
msgText = editText_chat_message.getText().toString();
}
Change url in doInBackground as :
String url = Util.send_chat_url+"?email_id="+mailId+"&message="+msgText;
you can create class for storing your parameter like i do,
Just create one class
example :
public class MyTaskParams
{
String mailId;
String message;
public MyTaskParams(String mailId, String message)
{
this.mailId = mailId;
this.message = message;
}
}
public class SendMessage extends AsyncTask<MyTaskParams, Void, String {
#Override
protected String doInBackground(MyTaskParams... params) {
String mailId = params[0].mailId;
String message = params[0].message;
String url = Util.send_chat_url+"?email_id="+ mailId +"&message="+ message;
}
}
so you can just call like this
MyTaskParams params = new MyTaskParams(editText_mail_id.getText().toString(),editText_chat_message.getText().toString());
SendMessage myTask = new SendMessage();
myTask.execute(params);
with this code you can call SendMessage Class from any activity, dont bind your asynctask with get text because if you do that you just can use SendMessage only in that activity
Hope this can help you.

How to update ProgressBar with respect to downloaded data while downloading text data from web using Asynctask in android

I want to show progressbar wrt to downloaded data from the web. Whether I have to create dynamically or have to reference by Id by creating it in xml.I am a little bit confused. Here is my code. Could you please tell me how?
package com.example.telugumovies;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
public class MainActivity extends ListActivity {
String category ="";
String[] cat = {"Upcoming","Telugu"};
private List<String> categories ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
categories = new ArrayList<String>();
int i=0;
for(i=0;i<2;i++)
{
categories.add(cat[i]+" Movies");
}
ArrayAdapter<String> myAdapter = new ArrayAdapter <String>(this,
R.layout.listview_rowlayout, R.id.tv, categories);
// assign the list adapter
setListAdapter(myAdapter);
}
// when an item of the list is clicked
#Override
protected void onListItemClick(ListView list, View view, int position, long id) {
super.onListItemClick(list, view, position, id);
Bundle giveCategory = new Bundle();
if(position == 0)
{
try {
new GetData().execute();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
}
}
else if(position == 1)
{
giveCategory.putString("cate", cat[position]);
Intent a = new Intent(MainActivity.this,Show_Years.class);
a.putExtras(giveCategory);
startActivity(a);
}
else
{
Toast.makeText(getApplicationContext(), "Sorry This option is not Available for Now ",
Toast.LENGTH_SHORT).show();
}
//String selectedItem = (String) getListView().getItemAtPosition(position);
}
class GetData extends AsyncTask<String,Integer,String>
{
ProgressBar pb ;
protected void onPreExecute()
{
pb = new ProgressBar(MainActivity.this);
pb.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
String alldata = "";
int flag=1;
String data = "";
URL url = null;
int i=0,j=0,count=0,c=0;
URLConnection con = null;
InputStream is = null;
String line = null;
try
{
url = new URL("http://www.filmibeat.com/telugu/upcoming-movies.html");
con = url.openConnection();
is = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
//System.out.println(line);
alldata = "";
flag=0;
if(line.contains("<h3"))
{j=0;
flag=1;
for(i=0;i<line.length();i++)
{
if(line.charAt(i)=='<')
{
j=1;
}
else if(j==1 && line.charAt(i)=='>')
{
j=0;
}
else if(j==0)
{
alldata = alldata + (line.charAt(i));
}
}
}
data=data+alldata;
if(flag==1)
{
data=data+"$";
}
}
System.out.println(data);
return data;
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
return data;
}
}
protected void onPostExecute(String someting)
{
Bundle givedata = new Bundle();
givedata.putString("moviedata",someting);
Intent a = new Intent(MainActivity.this,Show_upcomingmovies.class);
a.putExtras(givedata);
pb.setVisibility(View.INVISIBLE);
startActivity(a);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Using dynamically created progress bar or referencing it from an id, are both fine.
Using a reference from XML allows you to have more control on the progress bars appearance, as you would have designed it sepcifically for your need (like appearance, where it has to appear, etc..). But if that is not the case, you can use a dynamically created one as in your current code as well.
There is a lot of ways. One is to define ProgressDiaolog as a field in your AsyncTask, then add it to your onPreExecuted():
pDialog = new ProgressDialog(this);
pDialog.setMessage("some downloading massage");
pDialog.setIndeterminate(false);
pDialog.setMax(100); //you can adjust this
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(false);
pDialog.show();
Then you can update the progress by override updateProgress() in your AsyncTask and call pDialog.setProgress();

sending data from edit text with single button

![here there are 3 edit text box. where i am using json to check the login id and password details and another text box is for the selection of the server address. the only criteria is that all these should be done with a single button ie the login button.
can any one help me with the code]1
the code is as follows
package com.example.catxam;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.catxam.JSONParser;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.EditText;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
public class Login extends Activity {
private EditText inputUserid, inputPassword, server;
TextView forgotPassword;
private Button b1;
public String serve;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String Flag = "flag";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.login);
inputUserid = (EditText) findViewById(R.id.Username_edit);
inputPassword = (EditText) findViewById(R.id.User_password);
server = (EditText) findViewById(R.id.serverSelection);
forgotPassword = (TextView) findViewById(R.id.forgotPassword);
forgotPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent passForget = new Intent(getApplicationContext(),
ForgotPassword.class);
startActivity(passForget);
}
});
b1 = (Button) findViewById(R.id.loginbutton); // login button
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
new CreateNewUser().execute();
new SelectServerAddress().execute();
}
});
}
// this class is for selection of the server address
class SelectServerAddress extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... arg0) {
return null;
}
}
// this class is for the checking of the user login and password
//i.e. of first login and the next consecutive logins
class CreateNewUser extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Checking..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Checking creditenials
* */
protected String doInBackground(String... args) {
String user = inputUserid.getText().toString();
String pswrd = inputPassword.getText().toString();
//if (serve == "")
//{
//serve = "192.168.0.101/gly_prov_V1";
//}
//else
//{
//serve = "glydenlewis.esy.es";
//}
// URL to check username & password
final String url_check_user = "http://" + serve +"/gly_prov_V1/android_check.php";
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("uname", user));
params.add(new BasicNameValuePair("psd", pswrd));
params.add(new BasicNameValuePair("server",serve));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_check_user,
"POST", params);
// check log cat from response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
int flag_ck = json.getInt(Flag);
if (success == 1) {
if (flag_ck == 0)
{
//First Time Login By User
Intent i = new Intent(getApplicationContext(), UpdateDetails.class);
startActivity(i);
finish(); // closing this screen
}
else
{
// successfully login
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
finish(); // closing this screen
}
} else {
Toast.makeText(getApplicationContext(), "Wrong Credentials", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
}
You can execute tasks in serial manner. Take the output of first task as input to the second task.
But you have to implement a cancel mechanism if the activity is destroyed while your tasks is actually running. a simple approach is to make tasks references as a class member and cancel it when activity's onStop() method is called.
class static SelectServerAddress extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... urls) {
return getAddress(urls[0]);
}
#Override
protected void onPostExecute(String serverAddress) {
// Call login service
mLoginTask = new CreateNewUser(serverAddress);
mLoginTask.execute();
}
}
Edit:
Update button click listener code to this:
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
new SelectServerAdress().execute();
}
});
Then update SelectServerAdress class and add this method:
#Override
protected void onPostExecute(String serverAddress) {
serve = serverAddress;
new SelectServerAddress().execute();
}

UnknownHostException on parsing XML file in an Android application

I wrote an application Android to parse a XML file wich is situated online. I use JDOM and AsyncTask and it works great but only when I'm connected in WIFI.
When I'm connected in 3G, it doesn't work anymore. I've got the message "Caused by: java.net.UnknownHostException: Unable to resolve host "jeancdc.perso.sfr.fr": No address associated with hostname".
This is the log file : log.
In my Manifest.xml file, I've added the permissions :
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Could someone help me please ? Thanks by advance.
Below is my XMLReader class followed by my MainActivity class.
package fr.jcdc.exemple.jdomasynctaskxmlreader;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import android.util.Log;
public class XMLReader {
private Personnage[] personnages;
public XMLReader() {
super();
}
public void loading() {
Log.i("tag","fonction loading.");
try {
SAXBuilder builder = new SAXBuilder();
Document document = (Document) builder.build(new URL("http://jeancdc.perso.sfr.fr/fichierXML.xml"));
Element rootNode = document.getRootElement();
List<Element> charactersList = rootNode.getChildren("personnage");
personnages = new Personnage[charactersList.size()];
for (int i = 0; i < charactersList.size(); i++) {
Element node = (Element) charactersList.get(i);
personnages[i] = new Personnage();
personnages[i].setPrenom(node.getChildText("prenom"));
personnages[i].setNom(node.getChildText("nom"));
personnages[i].setFonction(node.getChildText("fonction"));
Log.i("tag", node.getChildText("prenom") + " " + node.getChildText("nom"));
}
}
catch (IOException ioex) {
Log.d("ioex", ioex.getMessage());
ioex.printStackTrace();
}
catch (JDOMException jdomex) {
Log.d("jdomex", jdomex.getMessage());
}
}
public Personnage[] getPersonnages() {
return personnages;
}
}
// Rajouter dans le fichier AndroidManifest.xml :
// - android:configChanges="orientation|screenSize" pour gérer le changement d'orientation
// et ainsi éviter le crash de l'application
// - la permission ACCESS_NETWORK_STATE
package fr.jcdc.exemple.jdomasynctaskxmlreader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class MainActivity extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected()) {
new GetXMLDataTask<Object>().execute();
}
else {
AlertDialogBuilder alertDialogBuilder = new AlertDialogBuilder(this);
alertDialogBuilder.setTitle("Pas de connexion");
alertDialogBuilder.setMessage("Veuillez vérifier votre connexion à Internet.");
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
private class GetXMLDataTask<XMLItem> extends AsyncTask<String, Void, List<XMLItem>> {
private XMLReader xmlReader = new XMLReader();
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setTitle("Téléchargement des données");
progressDialog.setMessage("Veuillez patienter.");
progressDialog.show();
}
#Override
protected List<XMLItem> doInBackground(String... arg0) {
xmlReader.loading();
return null;
}
#Override
protected void onPostExecute(List<XMLItem> result) {
try {
List<HashMap<String, String>> liste = new ArrayList<HashMap<String, String>>();
HashMap<String, String> hashMap;
for (int i = 0 ; i < xmlReader.getPersonnages().length ; i++) {
hashMap = new HashMap<String, String>();
hashMap.put("nom", xmlReader.getPersonnages()[i].getPrenom() + " " + xmlReader.getPersonnages()[i].getNom());
hashMap.put("fonction", xmlReader.getPersonnages()[i].getFonction());
liste.add(hashMap);
}
SimpleAdapter adapter = new SimpleAdapter(getApplication(), liste,
R.layout.liste_personnages, new String[] {"nom", "fonction"},
new int[] {R.id.tv_prenom_nom, R.id.tv_fonction});
ListView listView = (ListView) findViewById(android.R.id.list);
listView.setAdapter(adapter);
}
catch(NullPointerException e) {
e.printStackTrace();
}
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
#SuppressWarnings("unchecked")
HashMap<String,String> hmPersonnage = (HashMap<String,String>) l.getItemAtPosition(position);
Toast.makeText(this.getApplication(), hmPersonnage.get("nom"), Toast.LENGTH_SHORT).show();
}
}
"java.net.UnknownHostException: Unable to resolve host" Exception always occur when you don't provide access internet permission but you have added required permission then your host server is not responding within time because of internet speed, due to lac of internet speed this exception might occur.

Categories

Resources