i call below php webservice and get xml response and parse resonse and set it to hashmap.now i want save server response in offline mode .can i save data in offline mode.how plz give me answer.
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
try {
if (response.length() > 0) {
int code = Integer.parseInt(XMLManualParser.getTagValue(Constant.TAG_CODE, response));
if (code == 1) {
spinner.clear();
ArrayList<String> eventlist = XMLManualParser.getMultipleTagList(Constant.TAG_LIST, response);
for (int i = 0; i < eventlist.size(); ++i) {
String responseContent = eventlist.get(i);
HashMap<String, String> hashMap = new HashMap<String, String>();
String title = XMLManualParser.getTagValue(Constant.title, responseContent);
hashMap.put("title", title);
hashMap.put("id", XMLManualParser.getTagValue(Constant.id, responseContent));
hashMap.put("url", XMLManualParser.getTagValue(Constant.url, responseContent));
hashMap.put("balanceurl", XMLManualParser.getTagValue(Constant.balanceurl, responseContent));
spinner.add(hashMap);
}
} else {
Toast.makeText(SettingsEditActivity.this, "no data found", Toast.LENGTH_SHORT).show();
}
CustomSpinnerAdapter customSpinnerAdapter = new CustomSpinnerAdapter(SettingsEditActivity.this, spinner);
settingsBinding.splist.setAdapter(customSpinnerAdapter);
settingsBinding.splist.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
item = parent.getItemAtPosition(position).toString();
// Toast.makeText(parent.getContext(), "Android Custom Spinner Example Output..." + item, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
You can save your response into a file and get in offline
public static void saveDataSingleItemDetails(Context context,String file, MainListModel data) {
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = context.openFileOutput(file, MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (NullPointerException e) {
return;
}
ObjectOutputStream objectOutputStream = null;
try {
objectOutputStream = new ObjectOutputStream(fileOutputStream);
} catch (IOException | NullPointerException e) {
e.printStackTrace();
}
try {
if (objectOutputStream != null) {
objectOutputStream.writeObject(data);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (objectOutputStream != null) {
objectOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static MainListModel getSinglItemDetails(Context context,String file) {
MainListModel items = null;
FileInputStream fileInputStream = null;
try {
fileInputStream = context.openFileInput(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
return items;
} catch (NullPointerException e) {
return items;
}
ObjectInputStream objectInputStream = null;
try {
objectInputStream = new ObjectInputStream(fileInputStream);
} catch (IOException | NullPointerException e) {
e.printStackTrace();
return items;
}
try {
items = (MainListModel) objectInputStream.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
objectInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return items;
}
Related
public void getData(View view) {
try {
FileInputStream fileInput = openFileInput("user_data.txt");
InputStreamReader reader = new InputStreamReader(fileInput);
BufferedReader buffer = new BufferedReader(reader);
StringBuffer strBuffer = new StringBuffer();
String lines;
while ((lines = buffer.readLine()) != null) {
strBuffer.append(lines); //Вывод имени
}
textView3.setText(strBuffer.toString());
} catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} }
public void saveData (View view) {
String user_name = editSave.getText().toString();
try {
FileOutputStream fileOutput = openFileOutput("user_data.txt", MODE_PRIVATE);
fileOutput.write((user_name).getBytes());
fileOutput.close();
textView3.setText(user_name);
Toast.makeText(setting.this, " ", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Hello. I'm just learning. I need user_name to be called from any activity so I can insert it into the code that passes the text, right now I can't do it.
I will now try to explain what I want to get: textView.setText("random text" + user_name + "text random")
I would be very grateful if you could edit my code.
Following is my code and I want to get push notification when my device is offline or app is killed.
When my app is background I want to get notify by XMPP ejabberd server
IQ Class
class MyCustomIQ extends IQ {
String token = SharedPreferenceManager.getValue(getApplicationContext(), "DEVICE_TOKEN");
protected MyCustomIQ() {
super("query", "urn:xmpp:registernoti");
}
#Override
protected IQChildElementXmlStringBuilder getIQChildElementBuilder(IQChildElementXmlStringBuilder xml) {
xml.rightAngleBracket();
xml.element("token", token);
xml.element("devicetpye", "android");
return xml;
}
}
On connected
#Override
public void connected(XMPPConnection connection) {
Log.e(TAG, "connected: ");
MyCustomIQ iq = new MyCustomIQ();
iq.setType(IQ.Type.set);
try {
abstractXMPPConnection.sendIqWithResponseCallback(iq, new StanzaListener() {
#Override
public void processStanza(Stanza packet) throws SmackException.NotConnectedException, InterruptedException {
Log.e(TAG, "processStanza: " + packet.toString());
}
});
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Try following code for register device token on xmpp server
Register token stanza
<iq to="YourServer" type="set">
<register xmlns="https://android.googleapis.com/gcm" >
<key>API_KEY</key>
</register>
</iq>
1) way for register token
public void registerTokenTomod_gcm(final String deviceToken){
IQ iq=new IQ("register","https://android.googleapis.com/gcm") {
#Override
protected IQChildElementXmlStringBuilder getIQChildElementBuilder(IQChildElementXmlStringBuilder xml) {
xml.attribute("key",deviceToken);
xml.setEmptyElement();
return xml;
}
};
iq.setType(IQ.Type.set);
iq.setTo(AppConstants.CHAT_HOSTNAME);
debugLog("getpushDicsoInfo send stanza:"+iq.toXML());
try {
if(connection.isSmEnabled()) {
debugLog("sm enabled");
try {
connection.addStanzaIdAcknowledgedListener(iq.getStanzaId(), new StanzaListener() {
#Override
public void processPacket(Stanza stanza) throws SmackException.NotConnectedException {
debugLog("SendMessage addStanzaIdAcknowledgedListener ::" + stanza.toXML());
if(registerXmppListener!=null){
registerXmppListener.onStanzaIdAcknowledgedReceived(stanza);
}
}
});
} catch (StreamManagementException.StreamManagementNotEnabledException e) {
e.printStackTrace();
}
}
connection.sendStanza(iq);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
2) way to register token
public void registerTokenToXmpp(String deviceId,String deviceName,String deviceToken){
DataForm xep0004 = new DataForm(DataForm.Type.submit);
FormField token = new FormField("token");
token.addValue(deviceToken);
FormField device_id = new FormField("device-id");
device_id.addValue(deviceId);
FormField device_name = new FormField("device-name");
device_name.addValue(deviceName);
xep0004.addField(token);
xep0004.addField(device_id);
xep0004.addField(device_name);
AdHocCommandData stanza = new AdHocCommandData();
stanza.setTo("android");
stanza.setType(IQ.Type.set);
stanza.setStanzaId("0043423");
stanza.setNode("register-push-gcm");
stanza.setAction(AdHocCommand.Action.execute);
stanza.setForm(xep0004);
stanza.setFrom(connection.getUser());
debugLog("getpushDicsoInfo send stanza:"+stanza.toXML());
try {
if(connection.isSmEnabled()) {
debugLog("sm enabled");
try {
connection.addStanzaIdAcknowledgedListener(stanza.getStanzaId(), new StanzaListener() {
#Override
public void processPacket(Stanza stanza) throws SmackException.NotConnectedException {
debugLog("SendMessage addStanzaIdAcknowledgedListener ::" + stanza.toXML());
if(registerXmppListener!=null){
registerXmppListener.onStanzaIdAcknowledgedReceived(stanza);
}
}
});
} catch (StreamManagementException.StreamManagementNotEnabledException e) {
e.printStackTrace();
}
}
connection.sendStanza(stanza);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
UnRegister device token from server
private void unregisterToken(){
String deviceid="3524940..."; //sony
String tokenstring="GHkd7Ro2qtMg:XPA91bflkgklDeg..."; // sony
DataForm xep0004 = new DataForm(DataForm.Type.submit);
FormField token = new FormField("token");
token.addValue(tokenstring);
FormField device_id = new FormField("device-id");
device_id.addValue(deviceid);
FormField device_name = new FormField("device-name");
// device_name.addValue(devicename);
xep0004.addField(token);
xep0004.addField(device_id);
xep0004.addField(device_name);
AdHocCommandData stanza = new AdHocCommandData();
stanza.setTo("android");
stanza.setType(IQ.Type.set);
stanza.setStanzaId("0043423");
stanza.setNode("register-push-gcm");
stanza.setAction(AdHocCommand.Action.execute);
stanza.setForm(xep0004);
stanza.setFrom(connection.getUser());
debugLog("getpushDicsoInfo send stanza:"+stanza.toXML());
try {
if(connection.isSmEnabled()) {
debugLog("sm enabled");
try {
connection.addStanzaIdAcknowledgedListener(stanza.getStanzaId(), new StanzaListener() {
#Override
public void processPacket(Stanza stanza) throws SmackException.NotConnectedException {
debugLog("SendMessage addStanzaIdAcknowledgedListener ::" + stanza.toXML());
if(registerXmppListener!=null){
registerXmppListener.onStanzaIdAcknowledgedReceived(stanza);
}
}
});
} catch (StreamManagementException.StreamManagementNotEnabledException e) {
e.printStackTrace();
}
}
connection.sendStanza(stanza);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
}
When I click the first time on login button, data send to server and server received data in return on first click data not show on android client screen. When I pressed login button again it again send data and then it show data on client screen... plz help me. Why data is received on secind click i want my data recived on my first click?
Here is the code :
Client tcpip code...
public class SockProg {
private Socket socket;
DataOutputStream dataOutputStream;
DataInputStream dataInputStream;
String data;
String serverip = "192.168.1.7";
int serverport = 4444;
public void connetToServer(){
try {
socket = new Socket(serverip, serverport);
Log.i("AsyncTank", "doInBackgoung: Created Socket");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (socket.isConnected()) {
try {
dataOutputStream = new DataOutputStream(
socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void writeToStream(String message) {
try {
if (socket.isConnected()){
dataOutputStream.writeUTF(message.toString());
} else {
Log.i("AsynkTask", "writeToStream : Cannot write to stream, Socket is closed");
}
} catch (Exception e) {
Log.i("AsynkTask", "writeToStream : Writing failed");
}
}
public String readFromStream() {
String ret = null;
try {
if (socket.isConnected()) {
Log.i("AsynkTask", "readFromStream : Reading message");
ret=dataInputStream.readUTF();
Log.i("AsynkTask", "readFromStream : read "+ret);
} else {
Log.i("AsynkTask", "readFromStream : Cannot Read, Socket is closed");
}
} catch (Exception e) {
Log.i("AsynkTask", "readFromStream : Reading failed"+e.getClass());
}
return ret;
}
public void CloseSockets(){
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
here is the code of sychronized thread
public class TCP implements Runnable {
String data;
SockProg sp;
Thread thh;
private static String rdata;
public TCP(SockProg spr, String val) {
sp = spr;
data = val;
thh = new Thread(this);
thh.start();
}
#Override
public void run() {
synchronized(sp) { // synchronized block
//rdata= sp.DataSendRecive(data);
sp.connetToServer();
sp.writeToStream(data);
rdata=sp.readFromStream();
sp.CloseSockets();
}
}
public static String getData(){
return rdata;
}
}
here is code of Login Activity...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
msg = (TextView) findViewById(R.id.msg_log);
login = (Button) findViewById(R.id.btn_login);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// try{
txtph = (EditText) findViewById(R.id.txt_phnum);
txtpass = (EditText) findViewById(R.id.txt_pass);
ph = txtph.getText().toString();
pass = txtpass.getText().toString();
int ch = 0;
if (ph.equals("") || ph == null) {
msg.setText("Please Enter Mobile Number....\n");
ch++;
}
if (pass.equals("") || pass == null) {
if (ch == 0) {
msg.setText("Please Enter your Password....\n");
} else {
msg.append("Please Enter your Password....\n");
}
ch++;
}
if (ch == 0) {
ArrayList<String> ph_pass = new ArrayList<String>();
ph_pass.add(0, "LoginAccount");
ph_pass.add(1, ph);
ph_pass.add(2, pass);
SockProg sp=new SockProg();
TCP t=new TCP(sp, ph_pass.toString());
data=t.getData();
msg.setText(data);
}
}
});
}
This looks like a classic case of asynchronous coding delay. The TCP class is a runnable and therefor when it is called the first time (the first click on the login button) it starts running, but the Thread does not have enough time to finish
rdata=sp.readFromStream();
in the run() method, therefor data=t.getData(); does not return anything useful. The second click, provides the runnable with enough time populate the rdata with some data and therefor your program works.
When working with asynchrounous code, you need a better way to wait for code to complete what it is doing.
Why is rdata a static type? Make it non-static and then change the getData() method like this:
public synchronized String getData()
Basically the idea is I check to see if the web session is still valid, if not I start the main activity which logs the user in automatically.
I have this working, not sure if it's the best way to do it. If anyone has a better way please let me know.
Thanks
Useage:
#Override
public void onResume() {
super.onResume();
new LoginCheck(this,new Intent(this,MyActivity.class));
}
The Class
public class LoginCheck extends Application {
Intent home;
Activity activity;
public LoginCheck(Activity activity, Intent home) {
this.activity = activity;
this.home = home;
new Check().execute();
}
public class Check extends AsyncTask {
#Override
protected Object doInBackground(Object... objects) {
try {
InputStream is = null;
String result = "";
JSONObject jArray = null;
PersistentCookieStore myCookieStore = new PersistentCookieStore(MyApp.getAppContext());
//http post
DefaultHttpClient mClient = AppSettings.getClient();
try {
HttpPost request = new HttpPost(MyApp.getServiceUrl() + "/Api/Login/AmILoggedIn");
mClient.setCookieStore(myCookieStore);
HttpResponse response = mClient.execute(request);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
//convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
final String r = result;
final Intent i = home;
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
try {
JSONObject j = new JSONObject(r);
if (!j.getBoolean("Success")) {
try {
activity.startActivity(i);
} catch (Exception e) {
Log.e("log_tag", e.getMessage());
}
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
}
});
return true;
} catch (Exception e) {
}
return null;
}
}
}
Here is the cleaned up version
Use:
new LoginCheck() {
#Override
public void LoggedIn() {
//To change body of implemented methods use File | Settings | File Templates.
}
#Override
public void LoggedOut() {
//To change body of implemented methods use File | Settings | File Templates.
}
};
Class
public abstract class LoginCheck {
public LoginCheck(){
new Check().execute(true);
}
public class Check extends AsyncTask<Boolean,Boolean,Boolean>{
#Override
protected Boolean doInBackground(Boolean... objects) {
JSONStringer jsonSend = null;
try {
jsonSend = new JSONStringer()
.object()
.endObject();
} catch (JSONException e) {
Log.e("log_tag", "Error creating Json " + e.toString());
}
JSONObject result = JsonPost.postJSONtoURL(MyApp.getServiceUrl() + "/Api/Login/AmILoggedIn", jsonSend);
try {
if (result.getBoolean("Success")) {
return true;
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
try {
if (!result.getBoolean("Success")) {
return false;
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return false;
}
#Override
protected void onPostExecute(Boolean result){
if(result)
LoggedIn();
if(!result)
LoggedOut();
}
}
public abstract void LoggedIn();
public abstract void LoggedOut();
}
Merged with Need help in reading an xml file.
What am I doing wrong here?
String stringXmlContent;
try {
stringXmlContent = getEventsFromAnXML(this);
tv.setText(stringXmlContent);
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
button1.setOnClickListener(this);
}
private String getEventsFromAnXML(Activity activity)throws XmlPullParserException, IOException
{
StringBuffer stringBuffer = new StringBuffer();
String attVal = null;
String desc;
Resources res = activity.getResources();
XmlResourceParser xrp = res.getXml(R.xml.myxml);
try {
xrp.next();
int eventType = xrp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT)
{
if(eventType == XmlPullParser.START_DOCUMENT)
{
stringBuffer.append(" ");
}
if(eventType == XmlPullParser.START_TAG)
{
if(xrp.getName().equals("Number")){
attVal = xrp.getAttributeValue(0);
}
}
else if(eventType == XmlPullParser.TEXT)
{
if(xrp.getName().equals("Description") && attVal.equals("2")){
stringBuffer.append(" " + xrp.getText());
}
}
}
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return stringBuffer.toString();