Android App Posting to HTTP - Java for Android App Development

Alright so, this may get a bit confusing so feel free to ask me what the hell I'm talking about.
I am developing and app to run along side of a PHP web panel that is in development. I've been searching around for a way to hand logins on the app. The best method I could find that appears to suite our needs is to POST to HTTP. However while setting up the login file based on a tutorial I found, it doesn't seem to pull the data back properly. We are using a mysql database however we recently revamped the site and moved from mysql_query to PDO statements(not sure if that has anything to do with it).
Anyways what currently happens is you click login it checks the page and returns false all the time, unless the word "true" is echo'ed.
Here is my current code on the app side:
Code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Login extends Activity implements OnClickListener{
Button ok,back,exit;
TextView result;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ok = (Button)findViewById(R.id.button_login);
ok.setOnClickListener(this);
result = (TextView)findViewById(R.id.login_text);
}
public void postLoginData(){
new Thread(new Runnable(){
public void run(){
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("myurl");
try
{
EditText uname = (EditText)findViewById(R.id.usernamelogin);
String username = uname.getText().toString();
EditText pword = (EditText)findViewById(R.id.passwordlogin);
String password = pword.getText().toString();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("submit", "login"));
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Log.w("TMCP", "Execute HTTP Post Request");
HttpResponse response = httpclient.execute(httppost);
String str = inputStreamToString(response.getEntity().getContent()).toString();
Log.w("TMCP", str);
if(str.toString().equalsIgnoreCase("true"))
{
Log.w("TMCP", "TRUE");
}
else
{
Log.w("TMCP", "FALSE");
}
} catch(ClientProtocolException e){
e.printStackTrace();
} catch(IOException e){
e.printStackTrace();
}
}
}).start();
}
private StringBuilder inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Return full string
return total;
}
[user=439709]@override[/user]
public void onClick(View view) {
if(view == ok){
postLoginData();
}
}
}
Is there another way I should go about tackling this project? Besides logins I'm going to need the app to pull results from the database to create Lists, and Various other functions.
Thanks in advance for the help.
JakeR

I believe you're on the right track - this is how I implemented client-server communications in my app.
For transferring more complex data, I would recommend using PHP to print JSON arrays containing the data. Your app can then simply parse it to extract the data. You'd essentially be making your own 'api'.
Finally, when debugging your PHP scripts, I'd recommend you check out the postman rest client - it's powerful and makes developing 100x faster. https://chrome.google.com/webstore/detail/postman-rest-client/fdmmgilgnpjigdojojpjoooidkmcomcm?hl=en
I hope that answered your question, please feel free to ask anything!
Sent from my LG-P500 using xda app-developers app

I have done exactly the same thing with my forum viewing app. You have to post all data required, also any hidden input for example. Are you sure you posted all inputs?
I agree with the response above to use JSON format to obtain data as it is extremely easy and fast to use.
Sent from my NexusHD2 using xda app-developers app

When you use JSON the gson library from Google is a great help.

Related

[Q] Please help with tutorial code!

Good evening everyone! I am working on learning some java and I have made it to the notepad tutorial and when I go to run it on the emulator, I am getting a few errors, and I'm hoping someone here may be able to help.
Code:
package com.a8a.todolist;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ArrayAdapter;
import android.view.View.OnClickListener;
public class ToDoList extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
//Inflat your view
setContentView(R.layout.main);
//Get references to UI widgets
ListView myListView = (ListView)findViewById(R.id.myListView);
final EditText myEditText = (EditText)findViewById(R.id.myEditText);
//Create the array list of to do items
final ArrayList<String> todoItems = new ArrayList<String>();
//Create the array adapter to bind the array to the listview
final ArrayAdapter<String> aa;
[B]aa = new ArayAdapter<String>(this, android.R.layout.simple_list_item_1,todoItems);[/B] [I]Multiple markers at this line - ArayAdapter cannot be resolved to a type - Line breakpoint:ToDoList [line: 27] - onCreate[/I]
(Bundle)
//Bind the arary adapter to the listview.
myListView.setAdapter(aa);
[B]myEditText.setOnKeyListener(new OnKeyListener() {[/B] [I]OnKeyListener cannot be resolved to a type[/I]
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN)
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER)
{
todoItems.add(0, myEditText.getText().toString());
aa.notifyDataSetChanged();
myEditText.setText("");
return true;
}
return false;
}
});
}
}
The bolded text is whats getting the error and the italics are the error itself. Any help would be appreciated, if you are able to explain why the change needs to be made as well that would be much appreciated, so I can learn from my mistakes.
Thanks in advance!
ArayAdapter was miss-spelled ArrayAdapter
I was also missing an import for OnKeyListener (import android.view.View.OnKeyListener). If you don't import a class and try to use it, Java doesn't know what it is, so it tells you it doesn't recognize the type.

(Q) Load Custom system font from Extend TextView class.

Hello everyone.
i am trying to load a custom font from /system/fonts i use a custom extend TextView class
however i cant seem to let it load the font :/ i know i can load it through the assets but thats not what i want. i want it to load a custom ttf font from /system/fonts/***
because i would/will be using this Custom TextView class inside the frameworks.
Code:
package com.touchwizres.lifecompaniontext;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;
public class LifeCompanionTextView extends TextView {
TextView profilename;
String name;
public LifeCompanionTextView(final Context context, AttributeSet attrs) {
super(context, attrs);
profilename = (TextView) findViewById(R.id.life_companion_tag);
SharedPreferences sharedPreferences = context.getSharedPreferences("LifeCompanionFile",Context.MODE_PRIVATE);
name = sharedPreferences.getString("companionName","Life Companion");
profilename.setText(name);
BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context c, Intent i) {
name = i.getStringExtra("NAME");
profilename.setText(name);
SharedPreferences sharedPreferences = context.getSharedPreferences("LifeCompanionFile",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit(); //opens the editor
editor.putString("companionName", name); //true or false
editor.commit();
}
};
context.registerReceiver(mReceiver, new IntentFilter("lifecompanion.CHANGE_COMPANION"));
}
}
Here is my code.
if possible could someone help me ? i have tried some guides and couldnt seem to find a solution to this.
thanks
Best Regards Spacecaker.
SpaceCaker said:
Hello everyone.
i am trying to load a custom font from /system/fonts i use a custom extend TextView class
however i cant seem to let it load the font :/ i know i can load it through the assets but thats not what i want. i want it to load a custom ttf font from /system/fonts/***
because i would/will be using this Custom TextView class inside the frameworks.
Code:
package com.touchwizres.lifecompaniontext;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;
public class LifeCompanionTextView extends TextView {
TextView profilename;
String name;
public LifeCompanionTextView(final Context context, AttributeSet attrs) {
super(context, attrs);
profilename = (TextView) findViewById(R.id.life_companion_tag);
SharedPreferences sharedPreferences = context.getSharedPreferences("LifeCompanionFile",Context.MODE_PRIVATE);
name = sharedPreferences.getString("companionName","Life Companion");
profilename.setText(name);
BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context c, Intent i) {
name = i.getStringExtra("NAME");
profilename.setText(name);
SharedPreferences sharedPreferences = context.getSharedPreferences("LifeCompanionFile",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit(); //opens the editor
editor.putString("companionName", name); //true or false
editor.commit();
}
};
context.registerReceiver(mReceiver, new IntentFilter("lifecompanion.CHANGE_COMPANION"));
}
}
Here is my code.
if possible could someone help me ? i have tried some guides and couldnt seem to find a solution to this.
thanks
Best Regards Spacecaker.
Click to expand...
Click to collapse
i have fixed it.
Code:
package com.touchwizres.lifecompaniontext;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;
public class LifeCompanionTextView extends TextView {
TextView profilename;
String name;
public LifeCompanionTextView(final Context context, AttributeSet attrs) {
super(context, attrs);
profilename = (TextView) findViewById(R.id.life_companion_tag);
SharedPreferences sharedPreferences = context.getSharedPreferences("LifeCompanionFile",Context.MODE_PRIVATE);
name = sharedPreferences.getString("companionName","Life Companion");
profilename.setText(name);
Typeface tf = Typeface.createFromFile("/system/fonts/Cooljazz.ttf");
profilename.setTypeface(tf);
BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context c, Intent i) {
name = i.getStringExtra("NAME");
profilename.setText(name);
SharedPreferences sharedPreferences = context.getSharedPreferences("LifeCompanionFile",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit(); //opens the editor
editor.putString("companionName", name); //true or false
editor.commit();
}
};
context.registerReceiver(mReceiver, new IntentFilter("lifecompanion.CHANGE_COMPANION"));
}
}

Data That is Fetched From The Web Server Are Appending

I have this search function for my app that fetches data from web server using json, everything works completely except that everytime I search something, the data keeps on appending on my listview. For example if I search for a data with an id number 7 then press search button, the data is fetched and placed on the listview which what I want, but then if I search again the id number 7, there are now 2 instances of data with an id number of 7 in the listview. What I want is to refresh the listview for every search so that the only data that will appear on the listview is the current searched data.
MainActivity.java
Code:
package learn2crack.listview;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.EditText;
import learn2crack.listview.library.JSONParser;
public class MainActivity extends Activity {
ListView list;
TextView title;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//JSON Node Names
private static final String TAG_NEWS = "news";
private static final String TAG_TITLE = "title";
JSONArray android = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oslist = new ArrayList<HashMap<String, String>>();
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();
title = (TextView)findViewById(R.id.title);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
String url = "http://localhost/abc-news/news.php?json-request-news=";
EditText id = (EditText)findViewById(R.id.search_text);
url = url + id.getText().toString();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
@Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
android = json.getJSONArray(TAG_NEWS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String title = c.getString(TAG_TITLE);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, title);
oslist.add(map);
list=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_v,
new String[] { TAG_TITLE }, new int[] {
R.id.title });
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
I attached an image below to support this problem I'm encountering.
Code:
oslist.add(map);
you're adding to the list that drives the adapter, add does what it implies ... maybe you should go though some basics, copy and pasting code sometimes wastes more time that you think it would save in the long run.
Hope that helps
Can you explain it more clearly here?
clonedaccnt said:
Can you explain it more clearly here?
Click to expand...
Click to collapse
erm, add = add ? sorry to come across like this but not sure what you are expecting... a,b,c .add(d) == a,b,c,d
What do I need to do to my code so that the newly searched data will not append on the previous data that is fetched?
clonedaccnt said:
What do I need to do to my code so that the newly searched data will not append on the previous data that is fetched?
Click to expand...
Click to collapse
I thought that was clear, don't "add" to what you have? Are you aware of what an array is ? or a list? and an adapter? cause I think I would start there, you just keep adding to the list that powers the adapter. If you dont want to add to it just don't, either clear it or replace it.
so just to be clear, a list or map has the method .clear() <--- that clears it of all data
I've already solve the problem earlier, I was going to post that I've already solve it but found out that you've already replied on the thread, sorry. About the problem, yes I too used the .clear() of the ArrayList to clear the array before adding a new one, it's my first time to create an activity that pass the data on the same activity, I'm used to passing the data from one activity to another so I don't have a chance to encounter this kind of problem.
Anyways thanks for helping I will not have accomplished this without your help.

How do I change text in card views list?

I'm trying to update the text in my card view. I cannot figure out how to do it. I posted the code of my recyclerAdapter class below.
When a user clicks a card view it should update the text on the card view with a specified time.
Code:
package com.teamtreehouse.oslist;
import java.util.ArrayList;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.net.Uri;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import java.util.Calendar;
import android.content.Intent;
import java.text.SimpleDateFormat;
import java.util.Locale;
public class RecyclerAdapter extends RecyclerView.Adapter<FaucetHolder>
{
private ArrayList<Faucet> faucets;
private Context context;
private SharedPreferences sharedPref;
private String dateFormat = "h:mm a";
public RecyclerAdapter (ArrayList<Faucet> faucetsI,Context context) {
this.faucets = faucetsI;
this.context=context;
}
@Override
public FaucetHolder onCreateViewHolder(ViewGroup viewGroup, int i)
{
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_view,viewGroup,false);
FaucetHolder f = new FaucetHolder(v);
return f;
}
@Override
public void onBindViewHolder(FaucetHolder f, int k)
{
final Faucet faucet = faucets.get(k);
f.titleText.setText(faucet.getName());
f.titleText.setOnClickListener(new View.OnClickListener() {
public void onClick(View btn) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(faucet.getLink()));
setRenewal(faucet);
context.startActivity(intent);
}
});
}
@Override
public int getItemCount()
{
return faucets.size();
}
private void setRenewal(Faucet g) {
sharedPref = context.getSharedPreferences("myPref",0);
SharedPreferences.Editor edit = sharedPref.edit();
Calendar c = Calendar.getInstance();
long current = c.getTimeInMillis();
long future = current + g.getLength();
c.setTimeInMillis(future);
SimpleDateFormat df = new SimpleDateFormat(dateFormat,Locale.US);
String date = df.format(c.getTime());
edit.putString(g.getSPName(),date);
}
private void updateText(FaucetHolder f, Faucet g) {
sharedPref = context.getSharedPreferences("myPref",0);
String updatedTime = sharedPref.getString(g.getSPName(), null);
f.timeText.setText(updatedTime);
}
}
The full error text would be helpful. If you haven't done it before you can quickly check if something is wrong with your views in the adapter bei commenting them out.
Bump
Sent from my LG-F350K using Tapatalk

[App]Notification notified on Emulator but not visible on Phone

Hi Everyone! I was working on an app, which needed to give a remainder on a certain time, by triggering a notification. The app seemed to work fine on the emulator. But, the notification never shows up on a real phone.
The service which sends the broadcast.
Code:
package com.example.tanmay.yourdiary;
import android.annotation.TargetApi;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import java.text.SimpleDateFormat;
import java.util.Calendar;
/**
* Created by Tanmay on 22-01-2016.
*/
public class MyService extends IntentService {
public MyService() {
super("com.example.tanmay.yourdiary");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
final Context context = this;
final Intent i = new Intent("com.example.tanmay.yourdiary.MyReceiver");
i.setAction("com.example.tanmay.yourdiary.MyReceiver");
new Thread(new Runnable(){
public void run(){
while(true){
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
String g="";
g=sdf.format(c.getTime());
Log.i("dd",g);
if(g.equals("05:23")){
Log.i("d3d",g);
LocalBroadcastManager.getInstance(context).sendBroadcast(i);
try {
Thread.sleep(24*60*60*1000);
stopSelf();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(20000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
return START_STICKY;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
protected void onHandleIntent(Intent intent) {
}
}
The receiver
Code:
package com.example.tanmay.yourdiary;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
public class MyReceiver extends BroadcastReceiver {
public MyReceiver() {
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
Log.i("dfdfg", "bc rec");
NotificationCompat.Builder builder = new NotificationCompat.Builder(context).setSmallIcon(R.drawable.ic_launcher).setContentTitle("Reminder").setContentText("Time to write your thoughts!");
TaskStackBuilder taskstackbuilder = TaskStackBuilder.create(context);
taskstackbuilder.addParentStack(MainActivity.class);
Intent i = new Intent(context,Writing.class);
taskstackbuilder.addNextIntent(i);
PendingIntent ip = taskstackbuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(ip);
NotificationManager manager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(1,builder.build());
}
}
Try this code to see if it works on your phone or not
Code:
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mContext)
.setSmallIcon(R.drawable.ic_launcher).setContentTitle("Title").setContentText("Description text");
Intent resultIntent = new Intent(mContext, MainActivity.class);
resultIntent.putExtra(AN_ADITIONAL_EXTRA, "User clicked on the notification");
// Because clicking the notification opens a new ("special") activity, there's no need to create an artificial back stack.
PendingIntent resultPendingIntent = PendingIntent.getActivity(mContext, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
mBuilder.setAutoCancel(true);
// Sets an ID for the notification
int mNotificationId = 10; // give it an ID you recognize within your application
// Gets an instance of the NotificationManager service
NotificationManager mNotifyMgr = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
// Builds the notification and issues it.
mNotifyMgr.notify(mNotificationId, mBuilder.build());
And in your MainActivity.class under onNewIntent / onCreate
if(getIntent.getExtras() != null){
if(intent.hasExtra(AN_ADITIONAL_EXTRA)){
// User clicked on the notification, do something
}
}

Categories

Resources