Webserver to Android JSON parsing data - android

please have a look at my basic Android-Webserver code.
Data should from Android smartphone should be sent to a webserver, webserver should put data in database and then give the query:
{"query_result":"SUCCESS"}
(when i access the server-side script via browser i get this JSON-message, also the data is insterted into database)
The problem is that my app doesn't parse the JSON response correct or even doesn't get any response?
My code so far:
http://bits.works/view/466210bb
The code shows "Error parsing JSON data" on Android screen.
Call of method:
//Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
new SignupActivity(AndroidGPSTrackingActivity.this).execute(Double.toString(latitude), Double.toString(latitude), Double.toString(longitude), Double.toString(longitude), Double.toString(latitude));
Class with method:
public class SignupActivity extends AsyncTask<String, Void, String> {
private Context context;
public SignupActivity(Context context) {
this.context = context;
}
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg0) {
String fullName = arg0[0];
String userName = arg0[1];
String passWord = arg0[2];
String phoneNumber = arg0[3];
String emailAddress = arg0[4];
String link;
String data;
BufferedReader bufferedReader;
String result;
try {
data = "?fullname=" + URLEncoder.encode(fullName, "UTF-8");
data += "&username=" + URLEncoder.encode(userName, "UTF-8");
data += "&password=" + URLEncoder.encode(passWord, "UTF-8");
data += "&phonenumber=" + URLEncoder.encode(phoneNumber, "UTF-8");
data += "&emailaddress=" + URLEncoder.encode(emailAddress, "UTF-8");
link = "http://qqqqqtech/signup.php" + data;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
result = bufferedReader.readLine();
return result;
} catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
String jsonStr = result;
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String query_result = jsonObj.getString("query_result");
if (query_result.equals("SUCCESS")) {
Toast.makeText(context, "Data inserted.", Toast.LENGTH_SHORT).show();
} else if (query_result.equals("FAILURE")) {
Toast.makeText(context, "Data could not be inserted.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Couldn't connect to remote database.", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(context, "Error parsing JSON data.", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(context, "Couldn't get any JSON data.", Toast.LENGTH_SHORT).show();
}
}
}

Check the returned value from doInBackground before the line
String query_result = jsonObj.getString("query_result");
This is because doInBackground might have caught an exception and returned that instead of a valid response. So, make a Toast with jsonStr before trying to parse it to see what it contains.

Related

Android is not reading JSON array from PHP file

So I've been following a tutorial that shows how to connect android to MySQL db. I've done everything, but it didn't work. The PHP file works when i enter it's location in chrome -> it shows me the array in JSON format. However, in android it's not working maybe because I am hosting the file on a local server. Any help?
Thanks.
Android:
package com.example.mohammadel_ghali.icare;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
public class login extends AppCompatActivity {
String JSON_STRING ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
}
public void getJSON(View view){
new BackgroundTask().execute();
}
private class BackgroundTask extends AsyncTask<Void, Void, String> {
String JSON_URL;
#Override
protected void onPreExecute() {
JSON_URL ="10.0.2.2/ApplicationDemoNewNew/admin/android/json_get_login.php";
}
#Override
protected String doInBackground(Void... voids) {
try {
StringBuilder JSON_DATA = new StringBuilder();
URL url = new URL(JSON_URL);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream in = httpURLConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
while ((JSON_STRING = reader.readLine())!=null) {
JSON_DATA.append(JSON_STRING).append("\n");
}
return JSON_DATA.toString().trim();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
TextView json = (TextView) findViewById(R.id.tv_result);
json.setText(result);
}
}
}
PHP:
<?php
$mysql_host='localhost';
$mysql_user='root';
$mysql_password='root123';
$con = #mysqli_connect($mysql_host,$mysql_user,$mysql_password);
if(!$con){
die('Failed to connect to the database');//if not successful
}else{
//echo "Successfully connected to MySQL!";//if successful
if(#mysqli_select_db($con, 'application_database')){//selecting the database
//echo '<br>'."Connected to the specified database!";
}else{
die('<br>'."Could not connect to the specified database!");
}
}
$sql = "select * from users;";
$result = mysqli_query($con,$sql);
$response = array();
while($row = mysqli_fetch_array($result)){
array_push($response, array("id"=>$row[0],"username"=>$row[1],"password"=>$row[2],"first_name"=>$row[3],"last_name"=>$row[4]));
}
echo json_encode(array("server_response"=>$response));
mysqli_close($con);
?>
This is my entire class that takes in a JSON file......
Mine goes through a json provided by NFL and I grab the teams and scores
private class GetWeekScores extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(getApplication(),"Json Data is downloading",Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler httpHandler = new HttpHandler();
// Making a request to url and getting response
for (int i = 0; i <list.size(); i++) {
String url = NFL_LIVEUPDATE_URL + list.get(i) + "/" + list.get(i) + "_gtd.json";
String jsonStr = httpHandler.makeServiceCall(url);
Log.e(TAG, "Response from url: " + url);
if (jsonStr != null) {
try {
JSONObject id = new JSONObject(jsonStr);
JSONObject home = new JSONObject(jsonStr);
JSONObject away = new JSONObject(jsonStr);
// Getting JSON Array node
final JSONObject getid = id.getJSONObject(list.get(i));
JSONObject homeScore = getid.getJSONObject("home");
JSONObject homeScore2 = homeScore.getJSONObject("score");
homeTeamABBR = homeScore.getString("abbr");
getHomeScore = homeScore2.getString("T");
JSONObject awayScore = getid.getJSONObject("away");
JSONObject awayScore2 = awayScore.getJSONObject("score");
awayTeamABBR = awayScore.getString("abbr");
getAwayScore = awayScore2.getString("T");
HashMap<String, String> homeaway = new HashMap<>();
homeaway.put("matchup", awayTeamABBR + "vs" + homeTeamABBR);
homeaway.put("homeScore", homeTeamABBR + "->" + getHomeScore + " points ");
homeaway.put("awayScore", awayTeamABBR + "->" + getAwayScore + " points ");
if (Integer.parseInt(getHomeScore) > Integer.parseInt(getAwayScore)) {
homeaway.put("winner", homeTeamABBR);
} else {
homeaway.put("winner", awayTeamABBR);
}
gameIDList.add(homeaway);
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
MethodContants.showLog(TAG, "JSON File does not exist from NFL", true);
// runOnUiThread(new Runnable() {
// #Override
// public void run() {
// Toast.makeText(getApplicationContext(),
// "Couldn't get json from server. Check LogCat for possible errors!",
// Toast.LENGTH_LONG).show();
// }
// });
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
MethodContants.showLog(TAG, "Number of games being parsed through: " + list.size(), false);
for (int i = 0; i < gameIDList.size(); i++){
System.out.println(gameIDList.get(i).get("matchup") + " -> " + gameIDList.get(i).get("homeScore") + "-> " + gameIDList.get(i).get("awayScore") + ". " + gameIDList.get(i).get("winner") + " WON!");
}
}
}
I am not sure what else your PHP file does, but if you just need info from JSON, then create a JSON file....no need to create a PHP file.
I forgot to add the HttpHandler class.
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}

How do I show result from server response to app in Android?

I am developing and I want to show user login or not. Following is my code in this it shows correct response in Logcat but not show the message on app side(i.e login success or login failed message). How do I do this?
How do I parse json data in this?
Please suggest me!!
// Following is response from server shows inside Logcat
{
"login": [
{
"sessionid": 12973,
"responsetypes": "success"
}
]
}
// Following is my code
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
private EditText usernameEditText;
private EditText passwordEditText;
private Button sendGetReqButton;
TextView tv_forgot;
Button register;
Toolbar toolbar;
private boolean loggedIn = false;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
tv_forgot= (TextView)findViewById(R.id.tv_forgot);
tv_forgot.setOnClickListener(this);
usernameEditText = (EditText) findViewById(R.id.ed_email);
passwordEditText = (EditText) findViewById(R.id.ed_passowrd);
register = (Button) findViewById(R.id.btn_reg);
sendGetReqButton = (Button) findViewById(R.id.btn_login);
sendGetReqButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.btn_login){
// Get the values given in EditText fields
String userID = usernameEditText.getText().toString();
String password = passwordEditText.getText().toString();
System.out.println("Givennames is :" + userID + " Given password is :" + password);
// Pass those values to connectWithHttpGet() method
connectWithHttpGet(userID, password);
}
else {
Toast.makeText(LoginActivity.this, "Please Fill the fields", Toast.LENGTH_LONG).show();
}
}
private void connectWithHttpGet(String userID, String password) {
// Connect with a server is a time consuming process.
//Therefore we use AsyncTask to handle it
// From the three generic types;
//First type relate with the argument send in execute()
//Second type relate with onProgressUpdate method which I haven't use in this code
//Third type relate with the return type of the doInBackground method, which also the input type of the onPostExecute method
class HttpGetAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// As you can see, doInBackground has taken an Array of Strings as the argument
//We need to specifically get the givenUsername and givenPassword
String paramUsername = params[0];
String paramPassword = params[1];
System.out.println("userID" + paramUsername + " password is :" + paramPassword);
// Create an intermediate to connect with the Internet
HttpClient httpClient = new DefaultHttpClient();
// Sending a GET request to the web page that we want
// Because of we are sending a GET request, we have to pass the values through the URL
HttpGet httpGet = new HttpGet("http://www.example.com/ypAndroid/api/doLogin?userID=" + paramUsername + "&password=" + paramPassword);
try {
// execute(); executes a request using the default context.
// Then we assign the execution result to HttpResponse
HttpResponse httpResponse = httpClient.execute(httpGet);
System.out.println("httpResponse// getEntity() ; obtains the message entity of this response");
// getContent() ; creates a new InputStream object of the entity.
// Now we need a readable source to read the byte stream that comes as the httpResponse
InputStream inputStream = httpResponse.getEntity().getContent();
// We have a byte stream. Next step is to convert it to a Character stream
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
// Then we have to wraps the existing reader (InputStreamReader) and buffer the input
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
// InputStreamReader contains a buffer of bytes read from the source stream and converts these into characters as needed.
//The buffer size is 8K
//Therefore we need a mechanism to append the separately coming chunks in to one String element
// We have to use a class that can handle modifiable sequence of characters for use in creating String
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
// There may be so many buffered chunks. We have to go through each and every chunk of characters
//and assign a each chunk to bufferedStrChunk String variable
//and append that value one by one to the stringBuilder
while((bufferedStrChunk = bufferedReader.readLine()) != null){
stringBuilder.append(bufferedStrChunk);
}
// Now we have the whole response as a String value.
//We return that value then the onPostExecute() can handle the content
System.out.println("Returninge of doInBackground :" + stringBuilder.toString());
// If the Username and Password match, it will return "working" as response
// If the Username or Password wrong, it will return "invalid" as response
return stringBuilder.toString();
} catch (ClientProtocolException cpe) {
System.out.println("Exceptionrates caz of httpResponse :" + cpe);
cpe.printStackTrace();
} catch (IOException ioe) {
System.out.println("Secondption generates caz of httpResponse :" + ioe);
ioe.printStackTrace();
}
return null;
}
// Argument comes for this method according to the return type of the doInBackground() and
//it is the third generic type of the AsyncTask
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
System.out.println("Post result :" + result);
if(result.equals("success"))
Toast.makeText(getApplicationContext(), "HTTP GET is working...", Toast.LENGTH_LONG).show();
else {
Toast.makeText(getApplicationContext(), "Invalid...", Toast.LENGTH_LONG).show();
}
}
}
// Initialize the AsyncTask class
HttpGetAsyncTask httpGetAsyncTask = new HttpGetAsyncTask();
// Parameter we pass in the execute() method is relate to the first generic type of the AsyncTask
// We are passing the connectWithHttpGet() method arguments to that
httpGetAsyncTask.execute(userID, password);
}
}
You can do like this.
In the onPostExecute() method
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
System.out.println("Post result :" + result);
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray login = jsonObject.getJSONArray("login");
JSONObject jsonObject1 = login.getJSONObject(0);
// edited second, you response was responsetype, but I parsed was responsetypes,so you can have a look.
String responsetypes = jsonObject1.optString("responsetypes");
// edited
String sessionid = jsonObject1.getString("sessionid");
if (TextUtils.equals(responsetypes, "success")) {
Toast.makeText(getApplicationContext(), "HTTP GET is working...", Toast.LENGTH_LONG).show();
} else if (TextUtils.equals(responsetypes, "failure")) {
// edited
String message = jsonObject1.getString("message");
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
for example method get error response use volley.
private void getLogin() {
JSONObject param = new JSONObject();
try {
param.put("username", username.getText().toString());
param.put("password", password.getText().toString());
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.POST, url, param, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("login");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Log.d("sessionid>> ", jsonObject.getString("sessionid"));
}
dissmissPDialog();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("error >> ", error.toString());
streror = error.toString();
dissmissPDialog();
}
}
);
normal.add(jsonObjectRequest);
}
Update your onPostExecute() method like this.
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jsonObject1 = new JSONObject(result);
JSONArray jsonArray = jsonObject1.getJSONArray("login");
JSONObject jsonObjectLogin = jsonArray.getJSONObject(0);
String response = jsonObjectLogin.getString("responsetypes");
Toast.makeText(getApplicationContext(), +response, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
Let me know this is working or not.

android HttpGet/HttpPost parameters allways arrive as null to the server

I'm trying to send data to the server but it seems that I always send null values, any idea? The idea is to add a new customer through the mobile application to my database hosted in a server.
Here's my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nuevo_insert);
//etResponse = (EditText) findViewById(R.id.etResponse2);
etNombre = (EditText) findViewById(R.id.etNombre);
etApellido = (EditText) findViewById(R.id.etApellido);
etEdad = (EditText) findViewById(R.id.etEdad);
nombre = etNombre.getText().toString();
apellido = etApellido.getText().toString();
edad = etEdad.getText().toString();
}
public void insertar(View view) {
// Call AsyncTask to perform network operation on separate thread
// working in localhost you CAN'T put localhost in that address, you
// MUST put your IP address or it will crush
new HttpAsyncTask().execute("http://192.168.1.34/android/insertCustomer.php");
}
public static String GET(String url) {
InputStream inputStream = null;
String result = "";
try {
// create HttpClient
HttpClient httpClient = new DefaultHttpClient();
// make GET request to the given URL
HttpResponse httpResponse = httpClient.execute(new HttpGet(url+ "?nombre=" + nombre + "&apellido=" + apellido + "&edad="+ edad));
// receive response as InputStream
inputStream = httpResponse.getEntity().getContent();
// convert InputStream to string
if (inputStream != null) {
result = convertInputStreamToString(inputStream);
} else {
result = "No ha funcionat!";
}
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
return GET(urls[0]);
}
// onPostExecute displays the results of the AsyncTask
#Override
protected void onPostExecute(String result) {
String s = "";
Toast.makeText(getBaseContext(),getResources().getString(R.string.rebut), Toast.LENGTH_LONG).show();
JSONArray jArray;
try {
jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json = jArray.getJSONObject(i);
s = s + "Nom: " + json.getString("FirsName") + " "
+ json.getString("LastName") + "\n" + "Edat: "+ json.getInt("Age") + "\n\n";
}
etResponse.setText(s);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
This is my php file:
<?php
$con = mysql_connect('localhost', 'root', '');
if(!$con){
die("No se ha podido realizar la conexion: ".mysql_error());
}
mysql_select_db("TestDatabase", $con);
$nombre = $_GET['nombre'];
$apellido = $_GET['apellido'];
$edad = $_GET['edad'];
print_r($nombre."-".$apellido."-".$edad);
$result = mysql_query("insert into customer(FirsName, LastName, Age) values ('$nombre', '$apellido', '$edad')");
mysql_close($con);
?>
OK the problem was that I was retrieving the data from EditText boxes in the onCreate and I had to do it in the GET method :-)
If you are getting null value means that mean u r passing wrong type parameters or url may be wrong you do check it out
Change
HttpResponse httpResponse = httpClient.execute(new HttpGet(url+ "?nombre=" + nombre + "&apellido=" + apellido + "&edad="+ edad));
to this:
String request = url+ "?nombre=" + nombre + "&apellido=" + apellido + "&edad="+ edad;
Log.d("DEBUG", request);
HttpResponse httpResponse = httpClient.execute(request);
and see your logcat for your url, maybe it is broken.
if the url is ok, then try opening this url in your browser and check the results.

Consuming Web Service Android 4.0

Folks, I have an web service running on my PC, recently I changed my application from 2.2. for 4.0, and after that I cant connect to my WS anymore.
I'm looking for answers and found nothing.
My application refers the URL like this http://10.0.2.2:8080 ... But it dosn't work.
Heres my code:
private static final String URL_WS = "[this is not a link]http://10.0.2.2:8080/WS_TaxiShare/)";
public String login(String email, String password) throws Exception {
String[] resposta = new WSClient().get(URL_WS + "login/login/?login="+ email +"&password="+ password);
String saida = resposta[1];
if (resposta[0].equals("200")) {
return saida;
} else {
return saida;
}
}
Now the WSClient
public class WSClient {
public final String[] get(String url) {
String[] result = new String[2];
HttpGet httpget = new HttpGet(url);
HttpResponse response;
try {
Log.i("Get taxi", "Url -> " + url);
response = HttpClientSingleton.getHttpClientInstace().execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
result[0] = String.valueOf(response.getStatusLine().getStatusCode());
InputStream instream = entity.getContent();
result[1] = toString(instream);
instream.close();
Log.i("get", "Result from post JsonPost : " + result[0] + " : " + result[1]);
}
} catch (Exception e) {
Log.i("Exception no get WS taxi", "Exception ->" + e);
result[0] = "0";
result[1] = "Falha de rede!";
}
return result;
}
Someone can help me?
PS: My WS running on Glassfish
Well, i can solve my problem. Android 4.0 (I dont know when it begin), you cant call webservices on the main thread. And all you need to do is create a async method to do what you need in a separeated thread.
Here is my method
private class loginTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
try {
//Pegando o email e a senha da tela
String login = loginLogin.getText().toString();
String password = loginSenha.getText().toString();
WSTaxiShare ws = new WSTaxiShare();
Log.i("inciando login taxi", "Login -> " + login + " Senha -> " + password);
response = ws.login(login, password);
Log.i("String resposta taxi", response + "");
} catch (Exception e) {
Log.i("Exception Login taxi", e + "");
gerarToast("Não Foi possível logar");
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String strJson) {
try {
...
} catch (JSONException e) {
...
}
}
}
And here is the call button:
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
loginTask task = new loginTask();
task.execute(new String[] { "" });
}
});

how to get the names of all videos of a specific user on youtube by coding

I've written a big code and one of the options in my app is to retrieve all the matching results for this statement :
new conn().execute("https://gdata.youtube.com/feeds/api/videos?q=google&v=2&alt=json");
which are all the titles of videos contains "google" if q=google for example , now I want to retrieve all the related results if I entered a name of a user on youtube and get all his videos .. what is the modification for this statement to perform that ??
by replace the url by this :
http://gdata.youtube.com/feeds/api/videos?author=username&v=2&alt=json I can get all the videos for the same user :
new conn().execute("http://gdata.youtube.com/feeds/api/videos?author=username&v=2&alt=json");
This is the class of conn :
class conn extends AsyncTask<String, Integer, String>{
#Override
protected void onPreExecute() {
Log.d("after make conn", "ok");
progress.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
Log.d("doInBackground", "ok");
String s = GetUrlBody(arg0[0]);
return s;
}
#Override
protected void onPostExecute(String result) {
try{
Log.d("onPostExecute befor parsing", "ok");
/*************************************************************************/
JSONObject jo =(JSONObject) new JSONTokener(result).nextValue();
JSONObject feed = jo.optJSONObject("feed");
JSONArray ent = feed.optJSONArray("entry");
Log.d(" after parsing before loop", "ok");
/*************************************************************************/
for(int i = 0 ; i<ent.length() ; i++){
String title = ent.optJSONObject(i).
optJSONObject("title").optString("$t");
String views = ent.optJSONObject(i).optJSONObject("yt$statistics").optString("viewCount");
String authorName=ent.optJSONObject(i).optJSONArray("author").optJSONObject(0).optJSONObject("name").optString("$t");
String numDisLikes = ent.optJSONObject(i).
optJSONObject("yt$rating").optString("numDislikes");
String numLikes = ent.optJSONObject(i).
optJSONObject("yt$rating").optString("numLikes");
String description = ent.optJSONObject(i).
optJSONObject("media$group").optJSONObject("media$description").optString("$t");
String shortDescribtion=description.substring(0,49);
Log.d(" value of url", description);
String url=ent.optJSONObject(i).optJSONObject("media$group").optJSONArray("media$thumbnail").optJSONObject(0).optString("url");
Log.d(" value of array", url);
String link=ent.optJSONObject(i).optJSONArray("link").optJSONObject(0).optString("href");
Log.d(" after parsing in loop", "ok");
/*************************************************************************/
videoInfo.add("Title:"+title+"\n"+"By:"+authorName+"\n"+shortDescribtion);
Log.d(" after parsing in loop after list", "ok");
db.insertRow(title, numLikes, numDisLikes,views, authorName, link, description, url, vedioName);
Log.d(" after parsing in loop after insert", "ok");
}
Log.d("finish parsing ", "ok");
db.close();
/*************************************************************************/
Listadapter.notifyDataSetChanged();
Log.d(" after notify", "ok");
/*************************************************************************/
}catch(Exception exx) {
Log.getStackTraceString(exx.getCause().getCause());
}
/*************************************************************************/
progress.dismiss();
/*************************************************************************/
super.onPostExecute(result);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
String GetUrlBody (String Url ){
Log.d(" in GetUrlBody", "ok");
HttpClient cli = new DefaultHttpClient();
HttpGet g = new HttpGet(Url);
try{
HttpResponse res = cli.execute(g);
if(res.getStatusLine().getStatusCode() == 200){
String s =EntityUtils.toString(res.getEntity(), HTTP.UTF_8);
return s;
}else {
return "Not Found";
}
}catch(Exception exx){
Log.getStackTraceString(exx.getCause().getCause());
}
return "!";
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}

Categories

Resources