JSONParser can't request to server - java

I have a case where my second server I get different results when a request to the API with jsonparser. Always fail..
Server 1 | Server 2
On both servers (server 1 and 2) I made an example of exactly the same data, but when I make the request on the application turns on the first server to respond well, but the second server always responds with a null. How do I use the second server in order to run properly? I am very confused on this case..
I made ​​a simple application to perform experiments in case above :
package com.joris.androidjsonparsingfromurl;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
TextView uid;
TextView name1;
TextView email1;
Button Btngetdata;
// URL to get JSON Array
//private static String url = "http://newapi.bacaberita.com/statis.php";
private static String url = "http://api.berthojoris.com/babe/statis.php";
// JSON Node Names
private static final String TAG_ITEM = "items";
private static final String TAG_ISDISPLAY = "IsDisplay";
private static final String TAG_TITLE = "Title";
private static final String TAG_POST = "Post";
JSONArray user = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Utils.setPolicyThread();
Btngetdata = (Button) findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
uid = (TextView) findViewById(R.id.uid);
name1 = (TextView) findViewById(R.id.name);
email1 = (TextView) findViewById(R.id.email);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.setCanceledOnTouchOutside(false);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
if (result.length() > 0) {
pDialog.dismiss();
try {
// Getting JSON Array
user = result.getJSONArray(TAG_ITEM);
JSONObject c = user.getJSONObject(0);
// Storing JSON item in a Variable
String status = c.getString(TAG_ISDISPLAY);
String title = c.getString(TAG_TITLE);
String post = c.getString(TAG_POST);
// Set JSON Data in TextView
uid.setText(status);
name1.setText(title);
email1.setText(post);
Log.e("HASILNYA", status+title+post);
} catch (JSONException e) {
e.printStackTrace();
}
}else{
pDialog.dismiss();
Toast.makeText(getBaseContext(),
"Data Kosong Gan...", Toast.LENGTH_SHORT)
.show();
}
}
}
#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;
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.really_quit)
.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
finish();
}
}).setNegativeButton(R.string.no, null).show();
return true;
} else {
return super.onKeyDown(keyCode, event);
}
}
}
Is there a difference cause I can not make a request to the second server? Please help.. Thanks

Related

Getting json response in log.d but not inside app (code included)

I am trying to use the ProductHunt API to display a list of new posts in a ListView and further expand the list item on click.
On opening the app, the Progress bar appears but after that the app screen stays blank. I think there might be some error in my OnPostExecute method, because when I added a textview to display a string, its getting displayed but my listView is not getting displayed.
I used the standard Apache HttpClient for handling api requests.
I have 4 classes,
MainActivity.java
package com.emoji.apisoup;
/**
* Created by mdhalim on 16/05/16.
*/
import java.io.IOException;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import org.apache.http.HttpClientConnection;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.protocol.HTTP;
public class MainActivity extends Activity {
private ListView lvPosts;
private ProductHuntAdapter adapterPosts;
public static final String POST_DETAIL_KEY = "posts";
private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.phunt_main);
String serverURL = "https://api.producthunt.com/v1/posts/";
ArrayList<ProductHuntList> aPosts = new ArrayList<ProductHuntList>();
adapterPosts = new ProductHuntAdapter(MainActivity.this, aPosts);
lvPosts = (ListView) findViewById(R.id.lvPosts);
lvPosts.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
{
Intent i = new Intent(MainActivity.this, ProductHuntDetail.class);
i.putExtra(POST_DETAIL_KEY, adapterPosts.getItem(position));
startActivity(i);
}
}
});
new LongOperation().execute(serverURL);
}
private class LongOperation extends AsyncTask<String, Void, Void> {
private final HttpClient Content = new DefaultHttpClient();
private String Error = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
protected Void doInBackground(String... urls){
JSONArray items = null;
try {
HttpGet httpget = new HttpGet(urls[0]);
httpget.setHeader("Accept","application/json");
httpget.setHeader("Content-Type","application/json");
httpget.setHeader("Authorization","Bearer 2587aa878d7334e3c89794a6b73ebffb59a06c23b82cd0f789d2ab72d2417739");
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String jsonStr = Content.execute(httpget, responseHandler);
Log.d("Response: ", "> " + jsonStr);
JSONObject jsonObj = new JSONObject(jsonStr);
items = jsonObj.getJSONArray("posts");
// Parse json array into array of model objects
ArrayList<ProductHuntList> posts = ProductHuntList.fromJson(items);
// Load model objects into the adapter
for (ProductHuntList post : posts) {
adapterPosts.add(post);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
Error = e.getMessage();
cancel(true);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
ArrayList<ProductHuntList> aPosts = new ArrayList<ProductHuntList>();
adapterPosts = new ProductHuntAdapter(MainActivity.this, aPosts);
lvPosts.setAdapter(adapterPosts);
}
}
}
ProductHuntList.java containing the JSON Data model and deserializer and a static method for parsing an array of JSON
package com.emoji.apisoup;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.io.Serializable;
/**
* Created by mdhalim on 18/05/16.
*/
public class ProductHuntList implements Serializable {
private static final long serialVersionUID = -8959832007991513854L;
private String name;
private String tagline;
private String screenshot_url;
private String largePosterUrl;
private String discussion_Url;
private String created_at;
private int votes_count;
public String getNames() {
return name;
}
public String getCreated_at() {
return created_at;
}
public String getScreenshot_url() {
return screenshot_url;
}
public String getDiscussion_Url() {
return discussion_Url;
}
public int getVotes_count() {
return votes_count;
}
public String getLargePosterUrl() {
return largePosterUrl;
}
public String getTagline(){
return tagline;
}
public static ProductHuntList fromJson(JSONObject jsonObject) {
ProductHuntList b = new ProductHuntList();
try {
// Deserialize json into object fields
b.name = jsonObject.getString("name");
b.created_at = jsonObject.getString("created_at");
b.tagline = jsonObject.getString("tagline");
b.screenshot_url = jsonObject.getJSONObject("screenshot_url").getString("300px");
b.largePosterUrl = jsonObject.getJSONObject("screenshot_url").getString("850px");
b.votes_count = jsonObject.getInt("votes_count");
b.discussion_Url = jsonObject.getString("discussion_url");
} catch (JSONException e) {
e.printStackTrace();
return null;
}
// Return new object
return b;
}
public static ArrayList<ProductHuntList> fromJson(JSONArray jsonArray) {
ArrayList<ProductHuntList> posts = new ArrayList<ProductHuntList>(jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject productJson = null;
try {
productJson = jsonArray.getJSONObject(i);
} catch (Exception e) {
e.printStackTrace();
continue;
}
ProductHuntList post = ProductHuntList.fromJson(productJson);
if (post != null)
{
posts.add(post);
}
}
return posts;
}
}
ProductHuntAdapter.java this implements the ArrayAdapter
package com.emoji.apisoup;
/**
* Created by mdhalim on 18/05/16.
*/
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
/**
* Created by mdhalim on 18/05/16.
*/
public class ProductHuntAdapter extends ArrayAdapter<ProductHuntList> {
public ProductHuntAdapter(Context context, ArrayList<ProductHuntList> aPosts) {
super(context, 0, aPosts);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
ProductHuntList posts = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.item_product_hunt, null);
}
// Lookup view for data population
TextView name = (TextView) convertView.findViewById(R.id.name);
TextView created = (TextView) convertView.findViewById(R.id.created);
TextView tagline = (TextView) convertView.findViewById(R.id.tagline);
ImageView ivPosterImage = (ImageView) convertView.findViewById(R.id.ivPosterImage);
// Populate the data into the template view using the data object
name.setText(posts.getNames());
created.setText("Created On: " + posts.getCreated_at() + "%");
tagline.setText(posts.getTagline());
Picasso.with(getContext()).load(posts.getScreenshot_url()).into(ivPosterImage);
// Return the completed view to render on screen
return convertView;
}
}
and finally, a class implementing the activity for Item Details when a user clicks on any item on the list.
ProductHuntDetail
package com.emoji.apisoup;
/**
* Created by mdhalim on 18/05/16.
*/
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.text.Html;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
public class ProductHuntDetail extends Activity {
private ImageView ivPosterImage;
private TextView name;
private TextView discusUrl;
private TextView upvotes;
private TextView tagline;
private TextView created;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.product_hunt_detail);
// Fetch views
ivPosterImage = (ImageView) findViewById(R.id.ivPosterImage);
name = (TextView) findViewById(R.id.name);
discusUrl = (TextView) findViewById(R.id.discusUrl);
created = (TextView) findViewById(R.id.created);
upvotes = (TextView) findViewById(R.id.upvotes);
tagline = (TextView) findViewById(R.id.tagline);
// Load movie data
ProductHuntList posts = (ProductHuntList) getIntent().getSerializableExtra(MainActivity.POST_DETAIL_KEY);
loadMovie(posts);
}
// Populate the data for the movie
#SuppressLint("NewApi")
public void loadMovie(ProductHuntList posts) {
// Populate data
name.setText(posts.getNames());
upvotes.setText(Html.fromHtml("<b>Upvotes:</b> " + posts.getVotes_count() + "%"));
created.setText(posts.getCreated_at());
tagline.setText(posts.getTagline());
discusUrl.setText(Html.fromHtml("<b>Discussion Url:</b> " + posts.getDiscussion_Url()));
// R.drawable.large_movie_poster from
// http://content8.flixster.com/movie/11/15/86/11158674_pro.jpg -->
Picasso.with(this).load(posts.getLargePosterUrl()).
placeholder(R.drawable.large_movie_poster).
into(ivPosterImage);
}
}
I have been trying to debug this for hours :/
Your Async task is returning a void.
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
ArrayList<ProductHuntList> aPosts = new ArrayList<ProductHuntList>();
adapterPosts = new ProductHuntAdapter(MainActivity.this, aPosts);
lvPosts.setAdapter(adapterPosts);
}
As far as I can tell from the code, aPosts is empty.
I think your Async task should be -
AsyncTask<String, Void, ProductHuntAdapter>
and remove -
adapterPosts = new ProductHuntAdapter(MainActivity.this, aPosts);
You are creating and updating this in your doInBackground() method already.
I got it!
I didnt need to declare these lines again in my onPostExecute() method
ArrayList<ProductHuntList> aPosts = new ArrayList<ProductHuntList>();
adapterPosts = new ProductHuntAdapter(MainActivity.this, aPosts);
So bascially, my new onPostExecute() method goes like this
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
lvPosts.setAdapter(adapterPosts);
}
I had been trying to find this error for last 2 hours, it was harder since, I wasn't even getting any errors. As soon as I posted it on StackOverFlow, seems like I had a divine intervention.

How to populate a listview in Android using Volley

I am having trouble trying to get my andoid app to return a list view of all search results returned from a PHP files. I am using a wamp server to host the php files then I call them in the application using Volley. My problem is I can't get it to work with multiple return values. I have tried many different ways using videos online and resources from this site but i cant seem to get to work. This is my first Android application so I am new enough of the idea of a list view and json.
package com.example.mullally.newloginregister;
import android.app.AlertDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class HomeScreen extends AppCompatActivity {
String status = "";
ArrayAdapter<String> adapter;
ArrayList<String> items;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
final TextView createLink = (TextView) findViewById(R.id.tvCreate);
final TextView lostLink = (TextView) findViewById(R.id.tvLost);
final TextView foundLink = (TextView) findViewById(R.id.tvFound);
final Button btTest = (Button) findViewById(R.id.btTest);
createLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent registerIntent = new Intent(HomeScreen.this, CreateAdvert.class);
HomeScreen.this.startActivity(registerIntent);
}
});
lostLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
status="Lost";
// Response received from the server
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
String title = jsonResponse.getString("title");
String location = jsonResponse.getString("location");
Intent intent = new Intent(HomeScreen.this, BrowseLost.class);
intent.putExtra("title", title);
intent.putExtra("location", location);
HomeScreen.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(HomeScreen.this);
builder.setMessage("Something Went Wrong")
.setNegativeButton("Back", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
BrowseRequest browseRequest = new BrowseRequest(status, responseListener);
RequestQueue queue = Volley.newRequestQueue(HomeScreen.this);
queue.add(browseRequest);
}
});
foundLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
status = "Found";
// Response received from the server
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
String title = jsonResponse.getString("title");
String location = jsonResponse.getString("location");
Intent intent = new Intent(HomeScreen.this, BrowseFound.class);
intent.putExtra("title", title);
intent.putExtra("location", location);
HomeScreen.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(HomeScreen.this);
builder.setMessage("Something Went Wrong")
.setNegativeButton("Back", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
BrowseRequest browseRequest = new BrowseRequest(status, responseListener);
RequestQueue queue = Volley.newRequestQueue(HomeScreen.this);
queue.add(browseRequest);
}
});
btTest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
status = "Found";
// Response received from the server
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
String title = jsonResponse.getString("title");
String description = jsonResponse.getString("description");
String location = jsonResponse.getString("location");
String status = jsonResponse.getString("status");
String category = jsonResponse.getString("category");
Intent intent = new Intent(HomeScreen.this, ViewAdvert.class);
intent.putExtra("title", title);
intent.putExtra("description", description);
intent.putExtra("location", location);
intent.putExtra("status", status);
intent.putExtra("category", category);
HomeScreen.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(HomeScreen.this);
builder.setMessage("Something Went Wrong")
.setNegativeButton("Back", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
ViewRequest viewRequest = new ViewRequest(status, responseListener);
RequestQueue queue = Volley.newRequestQueue(HomeScreen.this);
queue.add(viewRequest);
}
});
This is the home screen. When a textview is clicked it would launch a request using volley in a seperate request class it is supposed to then return values add them to a json response opject and pass them into the Browse Lost class where it is then added to a listView.
This is the Request class:
package com.example.mullally.newloginregister;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import java.util.HashMap;
import java.util.Map;
/**
* Created by mullally on 14/04/2016.
*/
public class BrowseRequest extends StringRequest {
//192.168.11.2
private static final String BROWSE_REQUEST_URL = "http://192.168.11.5/android_content/GetAdvert.php";
private Map<String,String> params;
public BrowseRequest(String status, Response.Listener<String> listener){
super(Request.Method.POST, BROWSE_REQUEST_URL,listener, null);
params=new HashMap<>();
params.put("status", status);
}
#Override
public Map<String, String> getParams() {
return params;
}
}
And this is the activity that is launched to display the list :
package com.example.mullally.newloginregister;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class BrowseLost extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_browse_lost);
final ListView listView = (ListView) findViewById(R.id.listView);
final Intent intent= getIntent();
String title = intent.getStringExtra("title");
String location = intent.getStringExtra("location");
String details = title + " Location: " + location;
List<String> foundArray = new ArrayList<>();
foundArray.add(details);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_activated_2, android.R.id.text1, foundArray);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
String itemValue = (String) listView.getItemAtPosition(position);
// Show Alert
Toast.makeText(getApplicationContext(),
"Position :" + itemPosition + " ListItem : " + itemValue, Toast.LENGTH_LONG)
.show();
}
});
}
}
So basically I am trying to populate the listview with all values returned from the PHP. The php encodes the values into a json response eg.
[{"title":"Phone Found","location":"Dublin 6"},{"title":"test","location":"Dublin"},{"title":"dog","location":"Dublin 1"},{"title":"new","location":"Dublin 6W"}]

How can I create RequiredFieldValidattion in Android?

Here this is my code. It looks a bit complicated but it's working all fine. I just want to know how can I create when I click btnCreateProduct it should validate required edit text field and where to add those code?
package com.prinsapps.whatson;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Button;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
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.prinsapps.whatson.Addevent.CreateNewProduct;
public class Addevent extends Activity implements OnClickListener {
private ImageButton ib;
private Calendar cal;
private int day;
private int month;
private int year;
private EditText et;
//Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputName;
EditText inputDesc;
EditText inputCountry;
EditText inputdate;
EditText inputLink;
EditText inputOrg;
// url to create new product
private static String url_create_product = "http://-----------";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_event);
//Edit Text
inputName = (EditText) findViewById(R.id.inputName);
inputDesc = (EditText) findViewById(R.id.inputDesc);
inputCountry = (EditText) findViewById(R.id.inputCountry);
inputdate = (EditText) findViewById(R.id.inputdate);
inputLink = (EditText) findViewById(R.id.inputLink);
inputOrg = (EditText) findViewById(R.id.inputOrg);
// mDateButton = (Button) findViewById(R.id.date_button);
ib = (ImageButton) findViewById(R.id.imageButton1);
cal = Calendar.getInstance();
day = cal.get(Calendar.DAY_OF_MONTH);
month = cal.get(Calendar.MONTH);
year = cal.get(Calendar.YEAR);
et = (EditText) findViewById(R.id.inputdate);
ib.setOnClickListener(this);
// Create button
Button btnCreateProduct = (Button)
findViewById(R.id.btnCreateProduct);
// button click event
btnCreateProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
new CreateNewProduct().execute();
}
});
}
#Override
public void onClick(View v) {
showDialog(0);
}
#Override
#Deprecated
protected Dialog onCreateDialog(int id) {
return new DatePickerDialog(this, datePickerListener, year, month, day);
}
private DatePickerDialog.OnDateSetListener datePickerListener = new
DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
et.setText(selectedYear+"/"+(selectedMonth+1)+"/"+selectedDay);
}
};
/**
* Background Async Task to Create new product
* */
class CreateNewProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Addevent.this);
pDialog.setMessage("Creating Product..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
*
* */
protected String doInBackground(String... args) {
String name = inputName.getText().toString();
String description = inputDesc.getText().toString();
String country = inputCountry.getText().toString();
String date = inputdate.getText().toString();
String link = inputLink.getText().toString();
String org = inputOrg.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("description", description));
params.add(new BasicNameValuePair("country", country));
params.add(new BasicNameValuePair("date", date));
params.add(new BasicNameValuePair("link", link));
params.add(new BasicNameValuePair("org", org));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(),
AllProductsActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
use editText watcher
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
#Override
public void afterTextChanged(Editable editable) {
//Add your validations here
}
});
Yes it working fine now
#Override
public void onClick(View view) {
if ( ( !inputName.getText().toString().equals("")) &&
( !inputDesc.getText().toString().equals("")) &&
( !inputCountry.getText().toString().equals("")) &&
( !inputdate.getText().toString().equals(""))
)
{
// creating new product in background thread
new CreateNewProduct().execute();
}
else if ( ( !inputName.getText().toString().equals("")) )
{
Toast.makeText(getApplicationContext(),
"Please Enter Event Name", Toast.LENGTH_SHORT).show();
}
else if ( ( !inputDesc.getText().toString().equals("")) )
{
Toast.makeText(getApplicationContext(),
"Please Enter Event Description", Toast.LENGTH_SHORT).show();
}
else if ( ( !inputCountry.getText().toString().equals("")) )
{
Toast.makeText(getApplicationContext(),
"Please Enter Place or Country", Toast.LENGTH_SHORT).show();
}
else if ( ( !inputdate.getText().toString().equals("")) )
{
Toast.makeText(getApplicationContext(),
"Please Select Date When Event Start", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(),
"Event Details are empty", Toast.LENGTH_SHORT).show();
}
}
});
}
As I'm assuming, that you don't want to get empty your Textfield empty if you creating a product, I'd suggest to check wether the Strings of your EditTexts are null or empty.
This could look like this:
if(inputName.getText().equals("") || inputName.getText().equals(null)){
//Maybe show some message, that the given field ist required to be filled out
}
I would suggest to add this into your onClick() Method, or write an extra method to check wether an EditText is empty and return a boolean value. This could look like this:
public boolean notEmpty(EditText et){
if(et.getText().equals("") || et.getText().equals(null)){
return false;
}
return true;
}
And then check this for every EditText et before you create a new product.

Null Pointer Exception after some code moved to a custom Application class

Getting NullPointerException after I moved some of the code to a separate, custom application class called YambaApplication. This application posts to a Twitter enabled service. I checked the code 3 times, and cleaned the project 5 times:
Exception:
06-16 14:08:22.723: E/AndroidRuntime(392): Caused by:
java.lang.NullPointerException 06-16 14:08:22.723:
E/AndroidRuntime(392): at
com.user.yamba.StatusActivity$PostToTwitter.doInBackground(StatusActivity.java:70)
YambaApplication.java (here we initialize and return a twitter object):
package com.user.yamba;
import winterwell.jtwitter.Twitter;
import android.app.Application;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
public class YambaApplication extends Application implements
OnSharedPreferenceChangeListener {
private static final String TAG = YambaApplication.class.getSimpleName();
public Twitter twitter;
private SharedPreferences prefs;
#Override
public void onCreate() {
super.onCreate();
this.prefs = PreferenceManager.getDefaultSharedPreferences(this);
this.prefs.registerOnSharedPreferenceChangeListener(this);
Log.i(TAG, "onCreated");
}
#Override
public void onTerminate() {
super.onTerminate();
Log.i(TAG, "onTerminated");
}
#Override
public synchronized void onSharedPreferenceChanged(
SharedPreferences sharedPreferences, String key) {
this.twitter = null;
}
public synchronized Twitter getTwitter() {
if (this.twitter == null) {
String username, password, apiRoot;
username = this.prefs.getString("username", "");
password = this.prefs.getString("password", "");
apiRoot = this.prefs.getString("apiRoot",
"http://yamba.marakana.com/api");
if (!TextUtils.isEmpty(username) && !TextUtils.isEmpty(password)
&& !TextUtils.isEmpty(apiRoot)) {
this.twitter = new Twitter(username, password);
this.twitter.setAPIRootUrl(apiRoot);
}
}
return this.twitter;
}
}
StatusActivity.java (the first activity user sees with an EditText and an update button. Most of the code from YambaApplication class was inside this class.):
package com.user.yamba;
import winterwell.jtwitter.Twitter;
import winterwell.jtwitter.TwitterException;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class StatusActivity extends Activity implements OnClickListener,
TextWatcher {
private static final String TAG = "StatusActivity";
EditText editTextStatusUpdate;
Button buttonStatusUpdate;
TextView textViewCharacterCounter;
//SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_status);
// Find views
editTextStatusUpdate = (EditText) findViewById(R.id.editStatus);
buttonStatusUpdate = (Button) findViewById(R.id.buttonUpdate);
buttonStatusUpdate.setOnClickListener(this);
textViewCharacterCounter = (TextView) findViewById(R.id.editTextUpdateStatusCounter);
textViewCharacterCounter.setText(Integer.toString(140));
textViewCharacterCounter.setTextColor(Color.GREEN);
editTextStatusUpdate.addTextChangedListener(this);
//prefs = PreferenceManager.getDefaultSharedPreferences(this);
//prefs.registerOnSharedPreferenceChangeListener(this);
// Initialize twitter
// twitter = new Twitter("student", "password");
// twitter.setAPIRootUrl("http://yamba.marakana.com/api");
}
#Override
public void onClick(View v) {
String statusUpdate = editTextStatusUpdate.getText().toString();
new PostToTwitter().execute(statusUpdate);
Log.d(TAG, "onClicked");
}
// Async class to post of twitter
class PostToTwitter extends AsyncTask<String, Integer, String> {
// Async post status to twitter
#Override
protected String doInBackground(String... params) {
try {
YambaApplication yamba = ((YambaApplication) getApplication());
Twitter.Status status = yamba.getTwitter().updateStatus(params[0]); // EXCEPTION FIRED HERE
return status.text;
} catch (TwitterException e) {
Log.e(TAG, "Failed to connect to twitter service");
return "Failed to post";
}
}
// Called when there's status to be updated
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
// Not used
}
// Called once async task completed
#Override
protected void onPostExecute(String result) {
Toast.makeText(StatusActivity.this, result, Toast.LENGTH_LONG)
.show();
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// Not in use
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Not in use
}
// Update characters counter after text
// is changed(entered or deleted)
#Override
public void afterTextChanged(Editable statusText) {
int count = 140 - statusText.length();
textViewCharacterCounter.setText(Integer.toString(count));
textViewCharacterCounter.setTextColor(Color.GREEN);
if (count < 10) {
textViewCharacterCounter.setTextColor(Color.YELLOW);
}
if (count < 0) {
textViewCharacterCounter.setTextColor(Color.RED);
}
}
// When user taps on the menu hardware button inflate
// the menu resource
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
// Determine what item user tapped on the menu
// and start the item's activity
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.itemPrefs:
startActivity(new Intent(this, PrefsActivity.class));
break;
}
return true;
}
// private Twitter getTwitter() {
// if (twitter == null) {
// String username, password, apiRoot;
// username = prefs.getString("username", "");
// password = prefs.getString("password", "");
// apiRoot = prefs.getString("apiRoot",
// "http://yamba.marakana.com/api");
//
// // Connect to twitter
// twitter = new Twitter(username, password);
// twitter.setAPIRootUrl(apiRoot);
// }
// return twitter;
// }
// #Override
// public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
// String key) {
// // invalidate twitter
// twitter = null;
//
// }
}
Manifest (added this line to the application tag in the manifest):
android:name=".YambaApplication"
The first thing I saw were the new checks for the username and password to contain text.
Maybe try to debug if they both are set correctly and if a Twitter Object is returned from the Application, or simply null, because of those checks.
Null is because in YambaApplication you check:
if (!TextUtils.isEmpty(username) && !TextUtils.isEmpty(password)
&& !TextUtils.isEmpty(apiRoot)) {
...
}
If any field is empty you get twiter == null.

i want to call variables from one java class to different java class in android

Its like there are many class like Login.java, Updatedetails.java, Result.java etc.
Here is the java code for Login.java
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 static String serve;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// JSON Node names
private static final String resp = "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();
}
});
}
// 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
* */
protected void shradu() {
//super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Failed Login");
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();
serve = server.getText().toString();
if (serve.equals("web"))
serve = "glydenlewis.esy.es";
else if (serve.equals("g"))
serve = "192.168.1.4";
else if (serve.equals("r"))
serve = "192.168.0.100";
else if (serve.equals("v"))
serve = "192.168.0.100";
else
serve = "glydenlewis.esy.es";
// URL to check username & password
final String url_check_user = "http://" + serve + "/catxam/android_check.php";
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("uname", user));
params.add(new BasicNameValuePair("psd", pswrd));
// getting JSON Object
// Note that create product url accepts POST method
// this try is to catch if server address is wrong
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(resp);
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);
Toast.makeText(getApplicationContext(), "First Login, Please Update Your Details",Toast.LENGTH_SHORT).show();
startActivity(i);
finish(); // closing this screen
}
else
{
// successfully login
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
finish(); // closing this screen
}
} else {
// successfully login
Intent i = new Intent(getApplicationContext(), LogoStart.class);
startActivity(i);
finish(); // closing this screen
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
}
now for the UpdateDetails.java
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 android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.view.Window;
import android.view.WindowManager;
public class UpdateDetails extends Activity {
EditText inputName;
EditText inputAddress;
EditText inputPassword;
EditText confirmPassword;
EditText inputEmailId, inputMobileno;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// JSON Node names
private static final String resp = "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.updatedetails);
// Edit Text
inputName = (EditText) findViewById(R.id.editName);
inputAddress = (EditText) findViewById(R.id.editAddress);
inputPassword = (EditText) findViewById(R.id.editPassword);
confirmPassword=(EditText) findViewById(R.id.editConfirmPassword);
inputEmailId=(EditText) findViewById(R.id.editText2_emailid);
inputMobileno=(EditText) findViewById(R.id.editText1_mobile);
// Create button
Button update_details = (Button) findViewById(R.id.buttonUpdate);
// button click event
update_details.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (inputPassword == confirmPassword){
// updating user in background thread
new UpdateUserDetails().execute();
}
else {
//Some Sort Of Alert Box
Toast.makeText(getApplicationContext(), "Please Enter Valid Details", Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* Background Async Task to Create new product
* */
class UpdateUserDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(UpdateDetails.this);
pDialog.setMessage("Updating User Details.. Please wait");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* Updating User
* */
protected String doInBackground(String... args) {
String name = inputName.getText().toString();
String address = inputAddress.getText().toString();
String password = inputPassword.getText().toString();
String mobileno = inputMobileno.getText().toString();
String emailid = inputEmailId.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("address", address));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("mobile_no", mobileno));
params.add(new BasicNameValuePair("email_id",emailid));
final String url_user = "http://"+ Login.serve +"/catxam/android_update.php";
// getting JSON Object
JSONObject json = jsonParser.makeHttpRequest(url_user,"POST", params);
// check log cat from response
Log.d("Update Response", json.toString());
// check for success tag
try {
int success = json.getInt(resp);
if (success == 1) {
// successfully update user
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
Toast.makeText(getApplicationContext(), "Unsuccessful Updation", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
Now my question is that as i have declared all the server option only in login.java, which can be accessed by other class as Login.serve.
so i just want to make it simple and save all the address in GlobalVariableCall.java. and then these address would be accessed by different classes.
you can pass variables thru one activity to an other with the intent method wich is very simple...
Intent myIntent = new Intent(firstActivity.this, secondActivity.class);
myIntent.putExtra("data", data); //Optional parameters or data to be send to the next activity
firstActivity.this.startActivity(myIntent);
in that case you declare the global variable in the firstActivity... and you can putExtras as you want those are the variables that you are sending to the next activity
or you can instanciate the global variable class but you will lose the value of the variable when passing it thru one class to another...
i want to make a single class called as GlobalVariableCall where i am
declaring few variables such as public static Sting server.
So you have declared:
class GlobalVariableCall
{
public static String server="http://stackoverflow.com/questions/21634112/i-want-to-call-variables-from-one-java-class-to-different-java-class-in-android";
}
Then You can call this server variable from other Activity say Login.java like this:
OnCreate()
{
............
..............
String abc = GlobalVariableCall.server; // In this way abc will get the value of server.
}

Categories

Resources